UdpSocket.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. #region Fields
  18. private Socket _Socket;
  19. private int _LocalPort;
  20. #endregion
  21. public UdpSocket(Socket socket, int localPort, IPAddress ip)
  22. {
  23. if (socket == null) throw new ArgumentNullException("socket");
  24. _Socket = socket;
  25. _LocalPort = localPort;
  26. LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
  27. _Socket.Bind(new IPEndPoint(ip, _LocalPort));
  28. }
  29. public UdpSocket(Socket socket, IpEndPointInfo endPoint)
  30. {
  31. if (socket == null) throw new ArgumentNullException("socket");
  32. _Socket = socket;
  33. _Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
  34. }
  35. public IpAddressInfo LocalIPAddress
  36. {
  37. get;
  38. private set;
  39. }
  40. #region ISocket Members
  41. public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
  42. {
  43. ThrowIfDisposed();
  44. var tcs = new TaskCompletionSource<SocketReceiveResult>();
  45. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  46. var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
  47. state.TaskCompletionSource = tcs;
  48. #if NETSTANDARD1_6
  49. _Socket.ReceiveFromAsync(new ArraySegment<Byte>(state.Buffer), SocketFlags.None, state.RemoteEndPoint)
  50. .ContinueWith((task, asyncState) =>
  51. {
  52. if (task.Status != TaskStatus.Faulted)
  53. {
  54. var receiveState = asyncState as AsyncReceiveState;
  55. receiveState.RemoteEndPoint = task.Result.RemoteEndPoint;
  56. ProcessResponse(receiveState, () => task.Result.ReceivedBytes, LocalIPAddress);
  57. }
  58. }, state);
  59. #else
  60. _Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.RemoteEndPoint, ProcessResponse, state);
  61. #endif
  62. return tcs.Task;
  63. }
  64. public Task SendAsync(byte[] buffer, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
  65. {
  66. ThrowIfDisposed();
  67. if (buffer == null) throw new ArgumentNullException("messageData");
  68. if (endPoint == null) throw new ArgumentNullException("endPoint");
  69. var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
  70. #if NETSTANDARD1_6
  71. if (size != buffer.Length)
  72. {
  73. byte[] copy = new byte[size];
  74. Buffer.BlockCopy(buffer, 0, copy, 0, size);
  75. buffer = copy;
  76. }
  77. cancellationToken.ThrowIfCancellationRequested();
  78. _Socket.SendTo(buffer, ipEndPoint);
  79. return Task.FromResult(true);
  80. #else
  81. var taskSource = new TaskCompletionSource<bool>();
  82. try
  83. {
  84. _Socket.BeginSendTo(buffer, 0, size, SocketFlags.None, ipEndPoint, result =>
  85. {
  86. if (cancellationToken.IsCancellationRequested)
  87. {
  88. taskSource.TrySetCanceled();
  89. return;
  90. }
  91. try
  92. {
  93. _Socket.EndSend(result);
  94. taskSource.TrySetResult(true);
  95. }
  96. catch (Exception ex)
  97. {
  98. taskSource.TrySetException(ex);
  99. }
  100. }, null);
  101. }
  102. catch (Exception ex)
  103. {
  104. taskSource.TrySetException(ex);
  105. }
  106. //_Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(RemoteEndPoint.IPAddress), RemoteEndPoint.Port));
  107. return taskSource.Task;
  108. #endif
  109. }
  110. #endregion
  111. #region Overrides
  112. protected override void Dispose(bool disposing)
  113. {
  114. if (disposing)
  115. {
  116. var socket = _Socket;
  117. if (socket != null)
  118. socket.Dispose();
  119. }
  120. }
  121. #endregion
  122. #region Private Methods
  123. private static void ProcessResponse(AsyncReceiveState state, Func<int> receiveData, IpAddressInfo localIpAddress)
  124. {
  125. try
  126. {
  127. var bytesRead = receiveData();
  128. var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
  129. state.TaskCompletionSource.SetResult(
  130. new SocketReceiveResult
  131. {
  132. Buffer = state.Buffer,
  133. ReceivedBytes = bytesRead,
  134. RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
  135. LocalIPAddress = localIpAddress
  136. }
  137. );
  138. }
  139. catch (ObjectDisposedException)
  140. {
  141. state.TaskCompletionSource.SetCanceled();
  142. }
  143. catch (SocketException se)
  144. {
  145. if (se.SocketErrorCode != SocketError.Interrupted && se.SocketErrorCode != SocketError.OperationAborted && se.SocketErrorCode != SocketError.Shutdown)
  146. state.TaskCompletionSource.SetException(se);
  147. else
  148. state.TaskCompletionSource.SetCanceled();
  149. }
  150. catch (Exception ex)
  151. {
  152. state.TaskCompletionSource.SetException(ex);
  153. }
  154. }
  155. private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  156. {
  157. if (endpoint == null)
  158. {
  159. return null;
  160. }
  161. return NetworkManager.ToIpEndPointInfo(endpoint);
  162. }
  163. private void ProcessResponse(IAsyncResult asyncResult)
  164. {
  165. #if NET46
  166. var state = asyncResult.AsyncState as AsyncReceiveState;
  167. try
  168. {
  169. var bytesRead = state.Socket.EndReceiveFrom(asyncResult, ref state.RemoteEndPoint);
  170. var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
  171. state.TaskCompletionSource.SetResult(
  172. new SocketReceiveResult
  173. {
  174. Buffer = state.Buffer,
  175. ReceivedBytes = bytesRead,
  176. RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
  177. LocalIPAddress = LocalIPAddress
  178. }
  179. );
  180. }
  181. catch (ObjectDisposedException)
  182. {
  183. state.TaskCompletionSource.SetCanceled();
  184. }
  185. catch (Exception ex)
  186. {
  187. state.TaskCompletionSource.SetException(ex);
  188. }
  189. #endif
  190. }
  191. #endregion
  192. #region Private Classes
  193. private class AsyncReceiveState
  194. {
  195. public AsyncReceiveState(Socket socket, EndPoint remoteEndPoint)
  196. {
  197. this.Socket = socket;
  198. this.RemoteEndPoint = remoteEndPoint;
  199. }
  200. public EndPoint RemoteEndPoint;
  201. public byte[] Buffer = new byte[8192];
  202. public Socket Socket { get; private set; }
  203. public TaskCompletionSource<SocketReceiveResult> TaskCompletionSource { get; set; }
  204. }
  205. #endregion
  206. }
  207. }