2
0

UdpSocket.cs 8.4 KB

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