UdpSocket.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. private Socket _Socket;
  18. private int _LocalPort;
  19. private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
  20. {
  21. SocketFlags = SocketFlags.None
  22. };
  23. private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
  24. {
  25. SocketFlags = SocketFlags.None
  26. };
  27. private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
  28. private TaskCompletionSource<int> _currentSendTaskCompletionSource;
  29. private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
  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. private readonly AsyncCallback _defaultAsyncCallback = (i) => { };
  99. public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
  100. {
  101. EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
  102. return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
  103. }
  104. public SocketReceiveResult EndReceive(IAsyncResult result)
  105. {
  106. IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
  107. EndPoint remoteEndPoint = (EndPoint)sender;
  108. var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
  109. var buffer = (byte[]) result.AsyncState;
  110. return new SocketReceiveResult
  111. {
  112. ReceivedBytes = receivedBytes,
  113. RemoteEndPoint = ToIpEndPointInfo((IPEndPoint)remoteEndPoint),
  114. Buffer = buffer,
  115. LocalIPAddress = LocalIPAddress
  116. };
  117. }
  118. public Task<SocketReceiveResult> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  119. {
  120. var result = BeginReceive(buffer, offset, count, _defaultAsyncCallback);
  121. return Task.Factory.FromAsync(result, EndReceive);
  122. }
  123. public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
  124. {
  125. var buffer = new byte[8192];
  126. return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
  127. }
  128. public Task SendToAsync(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
  129. {
  130. var result = BeginSendTo(buffer, offset, size, endPoint, _defaultAsyncCallback, null);
  131. return Task.Factory.FromAsync(result, EndSendTo);
  132. }
  133. public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, AsyncCallback callback, object state)
  134. {
  135. var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
  136. return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
  137. }
  138. public int EndSendTo(IAsyncResult result)
  139. {
  140. return _Socket.EndSendTo(result);
  141. }
  142. protected override void Dispose(bool disposing)
  143. {
  144. if (disposing)
  145. {
  146. var socket = _Socket;
  147. if (socket != null)
  148. socket.Dispose();
  149. _sendLock.Dispose();
  150. var tcs = _currentReceiveTaskCompletionSource;
  151. if (tcs != null)
  152. {
  153. tcs.TrySetCanceled();
  154. }
  155. var sendTcs = _currentSendTaskCompletionSource;
  156. if (sendTcs != null)
  157. {
  158. sendTcs.TrySetCanceled();
  159. }
  160. }
  161. }
  162. private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
  163. {
  164. if (endpoint == null)
  165. {
  166. return null;
  167. }
  168. return NetworkManager.ToIpEndPointInfo(endpoint);
  169. }
  170. private class AsyncReceiveState
  171. {
  172. public AsyncReceiveState(Socket socket, EndPoint remoteEndPoint)
  173. {
  174. this.Socket = socket;
  175. this.RemoteEndPoint = remoteEndPoint;
  176. }
  177. public EndPoint RemoteEndPoint;
  178. public byte[] Buffer = new byte[8192];
  179. public Socket Socket { get; private set; }
  180. public TaskCompletionSource<SocketReceiveResult> TaskCompletionSource { get; set; }
  181. }
  182. }
  183. }