UdpSocket.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Model.Net;
  7. namespace Emby.Server.Implementations.Net
  8. {
  9. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  10. // Be careful to check any changes compile and work for all platform projects it is shared in.
  11. public sealed class UdpSocket : ISocket, IDisposable
  12. {
  13. private Socket _socket;
  14. private int _localPort;
  15. private bool _disposed = false;
  16. public Socket Socket => _socket;
  17. public IPAddress LocalIPAddress { get; }
  18. private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
  19. {
  20. SocketFlags = SocketFlags.None
  21. };
  22. private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
  23. {
  24. SocketFlags = SocketFlags.None
  25. };
  26. private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
  27. private TaskCompletionSource<int> _currentSendTaskCompletionSource;
  28. public UdpSocket(Socket socket, int localPort, IPAddress ip)
  29. {
  30. if (socket == null) throw new ArgumentNullException(nameof(socket));
  31. _socket = socket;
  32. _localPort = localPort;
  33. LocalIPAddress = ip;
  34. _socket.Bind(new IPEndPoint(ip, _localPort));
  35. InitReceiveSocketAsyncEventArgs();
  36. }
  37. private void InitReceiveSocketAsyncEventArgs()
  38. {
  39. var receiveBuffer = new byte[8192];
  40. _receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
  41. _receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
  42. var sendBuffer = new byte[8192];
  43. _sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
  44. _sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
  45. }
  46. private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
  47. {
  48. var tcs = _currentReceiveTaskCompletionSource;
  49. if (tcs != null)
  50. {
  51. _currentReceiveTaskCompletionSource = null;
  52. if (e.SocketError == SocketError.Success)
  53. {
  54. tcs.TrySetResult(new SocketReceiveResult
  55. {
  56. Buffer = e.Buffer,
  57. ReceivedBytes = e.BytesTransferred,
  58. RemoteEndPoint = e.RemoteEndPoint as IPEndPoint,
  59. LocalIPAddress = LocalIPAddress
  60. });
  61. }
  62. else
  63. {
  64. tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
  65. }
  66. }
  67. }
  68. private void _sendSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
  69. {
  70. var tcs = _currentSendTaskCompletionSource;
  71. if (tcs != null)
  72. {
  73. _currentSendTaskCompletionSource = null;
  74. if (e.SocketError == SocketError.Success)
  75. {
  76. tcs.TrySetResult(e.BytesTransferred);
  77. }
  78. else
  79. {
  80. tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
  81. }
  82. }
  83. }
  84. public UdpSocket(Socket socket, IPEndPoint endPoint)
  85. {
  86. if (socket == null) throw new ArgumentNullException(nameof(socket));
  87. _socket = socket;
  88. _socket.Connect(endPoint);
  89. InitReceiveSocketAsyncEventArgs();
  90. }
  91. public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
  92. {
  93. ThrowIfDisposed();
  94. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  95. return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
  96. }
  97. public int Receive(byte[] buffer, int offset, int count)
  98. {
  99. ThrowIfDisposed();
  100. return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
  101. }
  102. public SocketReceiveResult EndReceive(IAsyncResult result)
  103. {
  104. ThrowIfDisposed();
  105. var sender = new IPEndPoint(IPAddress.Any, 0);
  106. var remoteEndPoint = (EndPoint)sender;
  107. var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
  108. var buffer = (byte[])result.AsyncState;
  109. return new SocketReceiveResult
  110. {
  111. ReceivedBytes = receivedBytes,
  112. RemoteEndPoint = (IPEndPoint)remoteEndPoint,
  113. Buffer = buffer,
  114. LocalIPAddress = LocalIPAddress
  115. };
  116. }
  117. public Task<SocketReceiveResult> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  118. {
  119. ThrowIfDisposed();
  120. var taskCompletion = new TaskCompletionSource<SocketReceiveResult>();
  121. bool isResultSet = false;
  122. Action<IAsyncResult> callback = callbackResult =>
  123. {
  124. try
  125. {
  126. if (!isResultSet)
  127. {
  128. isResultSet = true;
  129. taskCompletion.TrySetResult(EndReceive(callbackResult));
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. taskCompletion.TrySetException(ex);
  135. }
  136. };
  137. var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback));
  138. if (result.CompletedSynchronously)
  139. {
  140. callback(result);
  141. return taskCompletion.Task;
  142. }
  143. cancellationToken.Register(() => taskCompletion.TrySetCanceled());
  144. return taskCompletion.Task;
  145. }
  146. public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
  147. {
  148. ThrowIfDisposed();
  149. var buffer = new byte[8192];
  150. return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
  151. }
  152. public Task SendToAsync(byte[] buffer, int offset, int size, IPEndPoint endPoint, CancellationToken cancellationToken)
  153. {
  154. ThrowIfDisposed();
  155. var taskCompletion = new TaskCompletionSource<int>();
  156. bool isResultSet = false;
  157. Action<IAsyncResult> callback = callbackResult =>
  158. {
  159. try
  160. {
  161. if (!isResultSet)
  162. {
  163. isResultSet = true;
  164. taskCompletion.TrySetResult(EndSendTo(callbackResult));
  165. }
  166. }
  167. catch (Exception ex)
  168. {
  169. taskCompletion.TrySetException(ex);
  170. }
  171. };
  172. var result = BeginSendTo(buffer, offset, size, endPoint, new AsyncCallback(callback), null);
  173. if (result.CompletedSynchronously)
  174. {
  175. callback(result);
  176. return taskCompletion.Task;
  177. }
  178. cancellationToken.Register(() => taskCompletion.TrySetCanceled());
  179. return taskCompletion.Task;
  180. }
  181. public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state)
  182. {
  183. ThrowIfDisposed();
  184. return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state);
  185. }
  186. public int EndSendTo(IAsyncResult result)
  187. {
  188. ThrowIfDisposed();
  189. return _socket.EndSendTo(result);
  190. }
  191. private void ThrowIfDisposed()
  192. {
  193. if (_disposed)
  194. {
  195. throw new ObjectDisposedException(nameof(UdpSocket));
  196. }
  197. }
  198. public void Dispose()
  199. {
  200. if (_disposed)
  201. {
  202. return;
  203. }
  204. _socket?.Dispose();
  205. _currentReceiveTaskCompletionSource?.TrySetCanceled();
  206. _currentSendTaskCompletionSource?.TrySetCanceled();
  207. _socket = null;
  208. _currentReceiveTaskCompletionSource = null;
  209. _currentSendTaskCompletionSource = null;
  210. _disposed = true;
  211. }
  212. }
  213. }