UdpSocket.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Security;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Emby.Common.Implementations.Networking;
  10. using MediaBrowser.Model.Net;
  11. namespace Emby.Common.Implementations.Net
  12. {
  13. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  14. // Be careful to check any changes compile and work for all platform projects it is shared in.
  15. internal sealed class UdpSocket : DisposableManagedObjectBase, ISocket
  16. {
  17. private Socket _Socket;
  18. private int _LocalPort;
  19. private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
  20. {
  21. SocketFlags = SocketFlags.None
  22. };
  23. private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
  24. {
  25. SocketFlags = SocketFlags.None
  26. };
  27. private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
  28. private TaskCompletionSource<int> _currentSendTaskCompletionSource;
  29. private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
  30. public UdpSocket(Socket socket, int localPort, IPAddress ip)
  31. {
  32. if (socket == null) throw new ArgumentNullException("socket");
  33. _Socket = socket;
  34. _LocalPort = localPort;
  35. LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
  36. _Socket.Bind(new IPEndPoint(ip, _LocalPort));
  37. InitReceiveSocketAsyncEventArgs();
  38. }
  39. private void InitReceiveSocketAsyncEventArgs()
  40. {
  41. var receiveBuffer = new byte[8192];
  42. _receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
  43. _receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
  44. var sendBuffer = new byte[8192];
  45. _sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
  46. _sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
  47. }
  48. private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
  49. {
  50. var tcs = _currentReceiveTaskCompletionSource;
  51. if (tcs != null)
  52. {
  53. _currentReceiveTaskCompletionSource = null;
  54. if (e.SocketError == SocketError.Success)
  55. {
  56. tcs.TrySetResult(new SocketReceiveResult
  57. {
  58. Buffer = e.Buffer,
  59. ReceivedBytes = e.BytesTransferred,
  60. RemoteEndPoint = ToIpEndPointInfo(e.RemoteEndPoint as IPEndPoint),
  61. LocalIPAddress = LocalIPAddress
  62. });
  63. }
  64. else
  65. {
  66. tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
  67. }
  68. }
  69. }
  70. private void _sendSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
  71. {
  72. var tcs = _currentSendTaskCompletionSource;
  73. if (tcs != null)
  74. {
  75. _currentSendTaskCompletionSource = null;
  76. if (e.SocketError == SocketError.Success)
  77. {
  78. tcs.TrySetResult(e.BytesTransferred);
  79. }
  80. else
  81. {
  82. tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
  83. }
  84. }
  85. }
  86. public UdpSocket(Socket socket, IpEndPointInfo endPoint)
  87. {
  88. if (socket == null) throw new ArgumentNullException("socket");
  89. _Socket = socket;
  90. _Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
  91. InitReceiveSocketAsyncEventArgs();
  92. }
  93. public IpAddressInfo LocalIPAddress
  94. {
  95. get;
  96. private set;
  97. }
  98. public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
  99. {
  100. ThrowIfDisposed();
  101. var tcs = new TaskCompletionSource<SocketReceiveResult>();
  102. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  103. var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
  104. state.TaskCompletionSource = tcs;
  105. cancellationToken.Register(() => tcs.TrySetCanceled());
  106. _receiveSocketAsyncEventArgs.RemoteEndPoint = receivedFromEndPoint;
  107. _currentReceiveTaskCompletionSource = tcs;
  108. try
  109. {
  110. var willRaiseEvent = _Socket.ReceiveFromAsync(_receiveSocketAsyncEventArgs);
  111. if (!willRaiseEvent)
  112. {
  113. _receiveSocketAsyncEventArgs_Completed(this, _receiveSocketAsyncEventArgs);
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. tcs.TrySetException(ex);
  119. }
  120. return tcs.Task;
  121. }
  122. public Task SendAsync(byte[] buffer, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
  123. {
  124. ThrowIfDisposed();
  125. if (buffer == null) throw new ArgumentNullException("messageData");
  126. if (endPoint == null) throw new ArgumentNullException("endPoint");
  127. var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
  128. #if NETSTANDARD1_6
  129. if (size != buffer.Length)
  130. {
  131. byte[] copy = new byte[size];
  132. Buffer.BlockCopy(buffer, 0, copy, 0, size);
  133. buffer = copy;
  134. }
  135. cancellationToken.ThrowIfCancellationRequested();
  136. _Socket.SendTo(buffer, ipEndPoint);
  137. return Task.FromResult(true);
  138. #else
  139. var taskSource = new TaskCompletionSource<bool>();
  140. try
  141. {
  142. _Socket.BeginSendTo(buffer, 0, size, SocketFlags.None, ipEndPoint, result =>
  143. {
  144. if (cancellationToken.IsCancellationRequested)
  145. {
  146. taskSource.TrySetCanceled();
  147. return;
  148. }
  149. try
  150. {
  151. _Socket.EndSend(result);
  152. taskSource.TrySetResult(true);
  153. }
  154. catch (Exception ex)
  155. {
  156. taskSource.TrySetException(ex);
  157. }
  158. }, null);
  159. }
  160. catch (Exception ex)
  161. {
  162. taskSource.TrySetException(ex);
  163. }
  164. return taskSource.Task;
  165. #endif
  166. //ThrowIfDisposed();
  167. //if (buffer == null) throw new ArgumentNullException("messageData");
  168. //if (endPoint == null) throw new ArgumentNullException("endPoint");
  169. //cancellationToken.ThrowIfCancellationRequested();
  170. //var tcs = new TaskCompletionSource<int>();
  171. //cancellationToken.Register(() => tcs.TrySetCanceled());
  172. //_sendSocketAsyncEventArgs.SetBuffer(buffer, 0, size);
  173. //_sendSocketAsyncEventArgs.RemoteEndPoint = NetworkManager.ToIPEndPoint(endPoint);
  174. //_currentSendTaskCompletionSource = tcs;
  175. //var willRaiseEvent = _Socket.SendAsync(_sendSocketAsyncEventArgs);
  176. //if (!willRaiseEvent)
  177. //{
  178. // _sendSocketAsyncEventArgs_Completed(this, _sendSocketAsyncEventArgs);
  179. //}
  180. //return tcs.Task;
  181. }
  182. public async Task SendWithLockAsync(byte[] buffer, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
  183. {
  184. ThrowIfDisposed();
  185. //await _sendLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  186. try
  187. {
  188. await SendAsync(buffer, size, endPoint, cancellationToken).ConfigureAwait(false);
  189. }
  190. finally
  191. {
  192. //_sendLock.Release();
  193. }
  194. }
  195. protected override void Dispose(bool disposing)
  196. {
  197. if (disposing)
  198. {
  199. var socket = _Socket;
  200. if (socket != null)
  201. socket.Dispose();
  202. _sendLock.Dispose();
  203. var tcs = _currentReceiveTaskCompletionSource;
  204. if (tcs != null)
  205. {
  206. tcs.TrySetCanceled();
  207. }
  208. var sendTcs = _currentSendTaskCompletionSource;
  209. if (sendTcs != null)
  210. {
  211. sendTcs.TrySetCanceled();
  212. }
  213. }
  214. }
  215. private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  216. {
  217. if (endpoint == null)
  218. {
  219. return null;
  220. }
  221. return NetworkManager.ToIpEndPointInfo(endpoint);
  222. }
  223. private void ProcessResponse(IAsyncResult asyncResult)
  224. {
  225. #if NET46
  226. var state = asyncResult.AsyncState as AsyncReceiveState;
  227. try
  228. {
  229. var bytesRead = state.Socket.EndReceiveFrom(asyncResult, ref state.RemoteEndPoint);
  230. var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
  231. state.TaskCompletionSource.SetResult(
  232. new SocketReceiveResult
  233. {
  234. Buffer = state.Buffer,
  235. ReceivedBytes = bytesRead,
  236. RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
  237. LocalIPAddress = LocalIPAddress
  238. }
  239. );
  240. }
  241. catch (ObjectDisposedException)
  242. {
  243. state.TaskCompletionSource.SetCanceled();
  244. }
  245. catch (Exception ex)
  246. {
  247. state.TaskCompletionSource.SetException(ex);
  248. }
  249. #endif
  250. }
  251. private class AsyncReceiveState
  252. {
  253. public AsyncReceiveState(Socket socket, EndPoint remoteEndPoint)
  254. {
  255. this.Socket = socket;
  256. this.RemoteEndPoint = remoteEndPoint;
  257. }
  258. public EndPoint RemoteEndPoint;
  259. public byte[] Buffer = new byte[8192];
  260. public Socket Socket { get; private set; }
  261. public TaskCompletionSource<SocketReceiveResult> TaskCompletionSource { get; set; }
  262. }
  263. }
  264. }