UdpSocket.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Emby.Server.Implementations.Networking;
  7. using MediaBrowser.Model.Net;
  8. namespace Emby.Server.Implementations.Net
  9. {
  10. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  11. // Be careful to check any changes compile and work for all platform projects it is shared in.
  12. public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
  13. {
  14. private Socket _Socket;
  15. private int _LocalPort;
  16. public Socket Socket
  17. {
  18. get { return _Socket; }
  19. }
  20. private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
  21. {
  22. SocketFlags = SocketFlags.None
  23. };
  24. private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
  25. {
  26. SocketFlags = SocketFlags.None
  27. };
  28. private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
  29. private TaskCompletionSource<int> _currentSendTaskCompletionSource;
  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 IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
  99. {
  100. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  101. return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
  102. }
  103. public int Receive(byte[] buffer, int offset, int count)
  104. {
  105. return _Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
  106. }
  107. public SocketReceiveResult EndReceive(IAsyncResult result)
  108. {
  109. IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
  110. EndPoint remoteEndPoint = (EndPoint)sender;
  111. var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
  112. var buffer = (byte[]) result.AsyncState;
  113. return new SocketReceiveResult
  114. {
  115. ReceivedBytes = receivedBytes,
  116. RemoteEndPoint = ToIpEndPointInfo((IPEndPoint)remoteEndPoint),
  117. Buffer = buffer,
  118. LocalIPAddress = LocalIPAddress
  119. };
  120. }
  121. public Task<SocketReceiveResult> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  122. {
  123. var taskCompletion = new TaskCompletionSource<SocketReceiveResult>();
  124. Action<IAsyncResult> callback = callbackResult =>
  125. {
  126. try
  127. {
  128. taskCompletion.TrySetResult(EndReceive(callbackResult));
  129. }
  130. catch (Exception ex)
  131. {
  132. taskCompletion.TrySetException(ex);
  133. }
  134. };
  135. var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback));
  136. if (result.CompletedSynchronously)
  137. {
  138. callback(result);
  139. }
  140. cancellationToken.Register(() => taskCompletion.TrySetCanceled());
  141. return taskCompletion.Task;
  142. }
  143. public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
  144. {
  145. var buffer = new byte[8192];
  146. return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
  147. }
  148. public Task SendToAsync(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
  149. {
  150. var taskCompletion = new TaskCompletionSource<int>();
  151. Action<IAsyncResult> callback = callbackResult =>
  152. {
  153. try
  154. {
  155. taskCompletion.TrySetResult(EndSendTo(callbackResult));
  156. }
  157. catch (Exception ex)
  158. {
  159. taskCompletion.TrySetException(ex);
  160. }
  161. };
  162. var result = BeginSendTo(buffer, offset, size, endPoint, new AsyncCallback(callback), null);
  163. if (result.CompletedSynchronously)
  164. {
  165. callback(result);
  166. }
  167. cancellationToken.Register(() => taskCompletion.TrySetCanceled());
  168. return taskCompletion.Task;
  169. }
  170. public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, AsyncCallback callback, object state)
  171. {
  172. var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
  173. return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
  174. }
  175. public int EndSendTo(IAsyncResult result)
  176. {
  177. return _Socket.EndSendTo(result);
  178. }
  179. protected override void Dispose(bool disposing)
  180. {
  181. if (disposing)
  182. {
  183. var socket = _Socket;
  184. if (socket != null)
  185. socket.Dispose();
  186. var tcs = _currentReceiveTaskCompletionSource;
  187. if (tcs != null)
  188. {
  189. tcs.TrySetCanceled();
  190. }
  191. var sendTcs = _currentSendTaskCompletionSource;
  192. if (sendTcs != null)
  193. {
  194. sendTcs.TrySetCanceled();
  195. }
  196. }
  197. }
  198. private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  199. {
  200. if (endpoint == null)
  201. {
  202. return null;
  203. }
  204. return NetworkManager.ToIpEndPointInfo(endpoint);
  205. }
  206. }
  207. }