UdpSocket.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
  16. {
  17. private Socket _Socket;
  18. private int _LocalPort;
  19. public Socket Socket
  20. {
  21. get { return _Socket; }
  22. }
  23. private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
  24. {
  25. SocketFlags = SocketFlags.None
  26. };
  27. private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
  28. {
  29. SocketFlags = SocketFlags.None
  30. };
  31. private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
  32. private TaskCompletionSource<int> _currentSendTaskCompletionSource;
  33. private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
  34. public UdpSocket(Socket socket, int localPort, IPAddress ip)
  35. {
  36. if (socket == null) throw new ArgumentNullException("socket");
  37. _Socket = socket;
  38. _LocalPort = localPort;
  39. LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
  40. _Socket.Bind(new IPEndPoint(ip, _LocalPort));
  41. InitReceiveSocketAsyncEventArgs();
  42. }
  43. private void InitReceiveSocketAsyncEventArgs()
  44. {
  45. var receiveBuffer = new byte[8192];
  46. _receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
  47. _receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
  48. var sendBuffer = new byte[8192];
  49. _sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
  50. _sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
  51. }
  52. private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
  53. {
  54. var tcs = _currentReceiveTaskCompletionSource;
  55. if (tcs != null)
  56. {
  57. _currentReceiveTaskCompletionSource = null;
  58. if (e.SocketError == SocketError.Success)
  59. {
  60. tcs.TrySetResult(new SocketReceiveResult
  61. {
  62. Buffer = e.Buffer,
  63. ReceivedBytes = e.BytesTransferred,
  64. RemoteEndPoint = ToIpEndPointInfo(e.RemoteEndPoint as IPEndPoint),
  65. LocalIPAddress = LocalIPAddress
  66. });
  67. }
  68. else
  69. {
  70. tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
  71. }
  72. }
  73. }
  74. private void _sendSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
  75. {
  76. var tcs = _currentSendTaskCompletionSource;
  77. if (tcs != null)
  78. {
  79. _currentSendTaskCompletionSource = null;
  80. if (e.SocketError == SocketError.Success)
  81. {
  82. tcs.TrySetResult(e.BytesTransferred);
  83. }
  84. else
  85. {
  86. tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
  87. }
  88. }
  89. }
  90. public UdpSocket(Socket socket, IpEndPointInfo endPoint)
  91. {
  92. if (socket == null) throw new ArgumentNullException("socket");
  93. _Socket = socket;
  94. _Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
  95. InitReceiveSocketAsyncEventArgs();
  96. }
  97. public IpAddressInfo LocalIPAddress
  98. {
  99. get;
  100. private set;
  101. }
  102. public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
  103. {
  104. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  105. return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
  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. _sendLock.Dispose();
  187. var tcs = _currentReceiveTaskCompletionSource;
  188. if (tcs != null)
  189. {
  190. tcs.TrySetCanceled();
  191. }
  192. var sendTcs = _currentSendTaskCompletionSource;
  193. if (sendTcs != null)
  194. {
  195. sendTcs.TrySetCanceled();
  196. }
  197. }
  198. }
  199. private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  200. {
  201. if (endpoint == null)
  202. {
  203. return null;
  204. }
  205. return NetworkManager.ToIpEndPointInfo(endpoint);
  206. }
  207. }
  208. }