UdpSocket.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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.Tasks;
  8. using Emby.Common.Implementations.Networking;
  9. using MediaBrowser.Model.Net;
  10. namespace Emby.Common.Implementations.Net
  11. {
  12. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  13. // Be careful to check any changes compile and work for all platform projects it is shared in.
  14. internal sealed class UdpSocket : DisposableManagedObjectBase, IUdpSocket
  15. {
  16. #region Fields
  17. private Socket _Socket;
  18. private int _LocalPort;
  19. #endregion
  20. #region Constructors
  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. #endregion
  30. public IpAddressInfo LocalIPAddress
  31. {
  32. get;
  33. private set;
  34. }
  35. #region IUdpSocket Members
  36. public Task<SocketReceiveResult> ReceiveAsync()
  37. {
  38. ThrowIfDisposed();
  39. var tcs = new TaskCompletionSource<SocketReceiveResult>();
  40. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  41. var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
  42. state.TaskCompletionSource = tcs;
  43. #if NETSTANDARD1_6
  44. _Socket.ReceiveFromAsync(new ArraySegment<Byte>(state.Buffer),SocketFlags.None, state.RemoteEndPoint)
  45. .ContinueWith((task, asyncState) =>
  46. {
  47. if (task.Status != TaskStatus.Faulted)
  48. {
  49. var receiveState = asyncState as AsyncReceiveState;
  50. receiveState.RemoteEndPoint = task.Result.RemoteEndPoint;
  51. ProcessResponse(receiveState, () => task.Result.ReceivedBytes, LocalIPAddress);
  52. }
  53. }, state);
  54. #else
  55. _Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.RemoteEndPoint, ProcessResponse, state);
  56. #endif
  57. return tcs.Task;
  58. }
  59. public Task SendAsync(byte[] buffer, int size, IpEndPointInfo endPoint)
  60. {
  61. ThrowIfDisposed();
  62. if (buffer == null) throw new ArgumentNullException("messageData");
  63. if (endPoint == null) throw new ArgumentNullException("endPoint");
  64. var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
  65. #if NETSTANDARD1_6
  66. if (size != buffer.Length)
  67. {
  68. byte[] copy = new byte[size];
  69. Buffer.BlockCopy(buffer, 0, copy, 0, size);
  70. buffer = copy;
  71. }
  72. _Socket.SendTo(buffer, ipEndPoint);
  73. return Task.FromResult(true);
  74. #else
  75. var taskSource = new TaskCompletionSource<bool>();
  76. try
  77. {
  78. _Socket.BeginSendTo(buffer, 0, size, SocketFlags.None, ipEndPoint, result =>
  79. {
  80. try
  81. {
  82. _Socket.EndSend(result);
  83. taskSource.TrySetResult(true);
  84. }
  85. catch (Exception ex)
  86. {
  87. taskSource.TrySetException(ex);
  88. }
  89. }, null);
  90. }
  91. catch (Exception ex)
  92. {
  93. taskSource.TrySetException(ex);
  94. }
  95. //_Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(RemoteEndPoint.IPAddress), RemoteEndPoint.Port));
  96. return taskSource.Task;
  97. #endif
  98. }
  99. #endregion
  100. #region Overrides
  101. protected override void Dispose(bool disposing)
  102. {
  103. if (disposing)
  104. {
  105. var socket = _Socket;
  106. if (socket != null)
  107. socket.Dispose();
  108. }
  109. }
  110. #endregion
  111. #region Private Methods
  112. private static void ProcessResponse(AsyncReceiveState state, Func<int> receiveData, IpAddressInfo localIpAddress)
  113. {
  114. try
  115. {
  116. var bytesRead = receiveData();
  117. var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
  118. state.TaskCompletionSource.SetResult(
  119. new SocketReceiveResult
  120. {
  121. Buffer = state.Buffer,
  122. ReceivedBytes = bytesRead,
  123. RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
  124. LocalIPAddress = localIpAddress
  125. }
  126. );
  127. }
  128. catch (ObjectDisposedException)
  129. {
  130. state.TaskCompletionSource.SetCanceled();
  131. }
  132. catch (SocketException se)
  133. {
  134. if (se.SocketErrorCode != SocketError.Interrupted && se.SocketErrorCode != SocketError.OperationAborted && se.SocketErrorCode != SocketError.Shutdown)
  135. state.TaskCompletionSource.SetException(se);
  136. else
  137. state.TaskCompletionSource.SetCanceled();
  138. }
  139. catch (Exception ex)
  140. {
  141. state.TaskCompletionSource.SetException(ex);
  142. }
  143. }
  144. private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  145. {
  146. if (endpoint == null)
  147. {
  148. return null;
  149. }
  150. return NetworkManager.ToIpEndPointInfo(endpoint);
  151. }
  152. private void ProcessResponse(IAsyncResult asyncResult)
  153. {
  154. #if NET46
  155. var state = asyncResult.AsyncState as AsyncReceiveState;
  156. try
  157. {
  158. var bytesRead = state.Socket.EndReceiveFrom(asyncResult, ref state.RemoteEndPoint);
  159. var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
  160. state.TaskCompletionSource.SetResult(
  161. new SocketReceiveResult
  162. {
  163. Buffer = state.Buffer,
  164. ReceivedBytes = bytesRead,
  165. RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
  166. LocalIPAddress = LocalIPAddress
  167. }
  168. );
  169. }
  170. catch (ObjectDisposedException)
  171. {
  172. state.TaskCompletionSource.SetCanceled();
  173. }
  174. catch (Exception ex)
  175. {
  176. state.TaskCompletionSource.SetException(ex);
  177. }
  178. #endif
  179. }
  180. #endregion
  181. #region Private Classes
  182. private class AsyncReceiveState
  183. {
  184. public AsyncReceiveState(Socket socket, EndPoint remoteEndPoint)
  185. {
  186. this.Socket = socket;
  187. this.RemoteEndPoint = remoteEndPoint;
  188. }
  189. public EndPoint RemoteEndPoint;
  190. public byte[] Buffer = new byte[8192];
  191. public Socket Socket { get; private set; }
  192. public TaskCompletionSource<SocketReceiveResult> TaskCompletionSource { get; set; }
  193. }
  194. #endregion
  195. }
  196. }