UdpSocket.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Rssdp.Infrastructure;
  11. namespace Rssdp
  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, IUdpSocket
  16. {
  17. #region Fields
  18. private System.Net.Sockets.Socket _Socket;
  19. private int _LocalPort;
  20. #endregion
  21. #region Constructors
  22. public UdpSocket(System.Net.Sockets.Socket socket, int localPort, string ipAddress)
  23. {
  24. if (socket == null) throw new ArgumentNullException("socket");
  25. _Socket = socket;
  26. _LocalPort = localPort;
  27. IPAddress ip = null;
  28. if (String.IsNullOrEmpty(ipAddress))
  29. ip = IPAddress.Any;
  30. else
  31. ip = IPAddress.Parse(ipAddress);
  32. _Socket.Bind(new IPEndPoint(ip, _LocalPort));
  33. if (_LocalPort == 0)
  34. _LocalPort = (_Socket.LocalEndPoint as IPEndPoint).Port;
  35. }
  36. #endregion
  37. #region IUdpSocket Members
  38. public System.Threading.Tasks.Task<ReceivedUdpData> ReceiveAsync()
  39. {
  40. ThrowIfDisposed();
  41. var tcs = new TaskCompletionSource<ReceivedUdpData>();
  42. System.Net.EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  43. var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
  44. state.TaskCompletionSource = tcs;
  45. #if NETSTANDARD1_6
  46. _Socket.ReceiveFromAsync(new System.ArraySegment<Byte>(state.Buffer), System.Net.Sockets.SocketFlags.None, state.EndPoint)
  47. .ContinueWith((task, asyncState) =>
  48. {
  49. if (task.Status != TaskStatus.Faulted)
  50. {
  51. var receiveState = asyncState as AsyncReceiveState;
  52. receiveState.EndPoint = task.Result.RemoteEndPoint;
  53. ProcessResponse(receiveState, () => task.Result.ReceivedBytes);
  54. }
  55. }, state);
  56. #else
  57. _Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, System.Net.Sockets.SocketFlags.None, ref state.EndPoint, new AsyncCallback(this.ProcessResponse), state);
  58. #endif
  59. return tcs.Task;
  60. }
  61. public Task SendTo(byte[] messageData, UdpEndPoint endPoint)
  62. {
  63. ThrowIfDisposed();
  64. if (messageData == null) throw new ArgumentNullException("messageData");
  65. if (endPoint == null) throw new ArgumentNullException("endPoint");
  66. #if NETSTANDARD1_6
  67. _Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port));
  68. return Task.FromResult(true);
  69. #else
  70. var taskSource = new TaskCompletionSource<bool>();
  71. try
  72. {
  73. _Socket.BeginSendTo(messageData, 0, messageData.Length, SocketFlags.None, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port), result =>
  74. {
  75. try
  76. {
  77. _Socket.EndSend(result);
  78. taskSource.TrySetResult(true);
  79. }
  80. catch (SocketException ex)
  81. {
  82. taskSource.TrySetException(ex);
  83. }
  84. catch (ObjectDisposedException ex)
  85. {
  86. taskSource.TrySetException(ex);
  87. }
  88. catch (InvalidOperationException ex)
  89. {
  90. taskSource.TrySetException(ex);
  91. }
  92. catch (SecurityException ex)
  93. {
  94. taskSource.TrySetException(ex);
  95. }
  96. }, null);
  97. }
  98. catch (SocketException ex)
  99. {
  100. taskSource.TrySetException(ex);
  101. }
  102. catch (ObjectDisposedException ex)
  103. {
  104. taskSource.TrySetException(ex);
  105. }
  106. catch (SecurityException ex)
  107. {
  108. taskSource.TrySetException(ex);
  109. }
  110. //_Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port));
  111. return taskSource.Task;
  112. #endif
  113. }
  114. #endregion
  115. #region Overrides
  116. protected override void Dispose(bool disposing)
  117. {
  118. if (disposing)
  119. {
  120. var socket = _Socket;
  121. if (socket != null)
  122. socket.Dispose();
  123. }
  124. }
  125. #endregion
  126. #region Private Methods
  127. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions via task methods should be reported by task completion source, so this should be ok.")]
  128. private static void ProcessResponse(AsyncReceiveState state, Func<int> receiveData)
  129. {
  130. try
  131. {
  132. var bytesRead = receiveData();
  133. var ipEndPoint = state.EndPoint as IPEndPoint;
  134. state.TaskCompletionSource.SetResult(
  135. new ReceivedUdpData()
  136. {
  137. Buffer = state.Buffer,
  138. ReceivedBytes = bytesRead,
  139. ReceivedFrom = new UdpEndPoint()
  140. {
  141. IPAddress = ipEndPoint.Address.ToString(),
  142. Port = ipEndPoint.Port
  143. }
  144. }
  145. );
  146. }
  147. catch (ObjectDisposedException)
  148. {
  149. state.TaskCompletionSource.SetCanceled();
  150. }
  151. catch (SocketException se)
  152. {
  153. if (se.SocketErrorCode != SocketError.Interrupted && se.SocketErrorCode != SocketError.OperationAborted && se.SocketErrorCode != SocketError.Shutdown)
  154. state.TaskCompletionSource.SetException(se);
  155. else
  156. state.TaskCompletionSource.SetCanceled();
  157. }
  158. catch (Exception ex)
  159. {
  160. state.TaskCompletionSource.SetException(ex);
  161. }
  162. }
  163. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions via task methods should be reported by task completion source, so this should be ok.")]
  164. private void ProcessResponse(IAsyncResult asyncResult)
  165. {
  166. #if NET46
  167. var state = asyncResult.AsyncState as AsyncReceiveState;
  168. try
  169. {
  170. var bytesRead = state.Socket.EndReceiveFrom(asyncResult, ref state.EndPoint);
  171. var ipEndPoint = state.EndPoint as IPEndPoint;
  172. state.TaskCompletionSource.SetResult(
  173. new ReceivedUdpData()
  174. {
  175. Buffer = state.Buffer,
  176. ReceivedBytes = bytesRead,
  177. ReceivedFrom = new UdpEndPoint()
  178. {
  179. IPAddress = ipEndPoint.Address.ToString(),
  180. Port = ipEndPoint.Port
  181. }
  182. }
  183. );
  184. }
  185. catch (ObjectDisposedException)
  186. {
  187. state.TaskCompletionSource.SetCanceled();
  188. }
  189. catch (SocketException se)
  190. {
  191. if (se.SocketErrorCode != SocketError.Interrupted && se.SocketErrorCode != SocketError.OperationAborted && se.SocketErrorCode != SocketError.Shutdown)
  192. state.TaskCompletionSource.SetException(se);
  193. else
  194. state.TaskCompletionSource.SetCanceled();
  195. }
  196. catch (Exception ex)
  197. {
  198. state.TaskCompletionSource.SetException(ex);
  199. }
  200. #endif
  201. }
  202. #endregion
  203. #region Private Classes
  204. private class AsyncReceiveState
  205. {
  206. public AsyncReceiveState(System.Net.Sockets.Socket socket, EndPoint endPoint)
  207. {
  208. this.Socket = socket;
  209. this.EndPoint = endPoint;
  210. }
  211. public EndPoint EndPoint;
  212. public byte[] Buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize];
  213. public System.Net.Sockets.Socket Socket { get; private set; }
  214. public TaskCompletionSource<ReceivedUdpData> TaskCompletionSource { get; set; }
  215. }
  216. #endregion
  217. }
  218. }