2
0

UdpServer.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. using System.Threading;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Model.Logging;
  6. using System;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Server.Implementations.Udp
  13. {
  14. /// <summary>
  15. /// Provides a Udp Server
  16. /// </summary>
  17. public class UdpServer : IDisposable
  18. {
  19. /// <summary>
  20. /// The _logger
  21. /// </summary>
  22. private readonly ILogger _logger;
  23. /// <summary>
  24. /// The _network manager
  25. /// </summary>
  26. private readonly INetworkManager _networkManager;
  27. /// <summary>
  28. /// The _HTTP server
  29. /// </summary>
  30. private readonly IHttpServer _httpServer;
  31. /// <summary>
  32. /// The _server configuration manager
  33. /// </summary>
  34. private readonly IServerConfigurationManager _serverConfigurationManager;
  35. private bool _isDisposed;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="UdpServer" /> class.
  38. /// </summary>
  39. /// <param name="logger">The logger.</param>
  40. /// <param name="networkManager">The network manager.</param>
  41. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  42. /// <param name="httpServer">The HTTP server.</param>
  43. public UdpServer(ILogger logger, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager, IHttpServer httpServer)
  44. {
  45. _logger = logger;
  46. _networkManager = networkManager;
  47. _serverConfigurationManager = serverConfigurationManager;
  48. _httpServer = httpServer;
  49. }
  50. /// <summary>
  51. /// Raises the <see cref="E:MessageReceived" /> event.
  52. /// </summary>
  53. /// <param name="e">The <see cref="UdpMessageReceivedEventArgs"/> instance containing the event data.</param>
  54. private async void OnMessageReceived(UdpMessageReceivedEventArgs e)
  55. {
  56. const string context = "Server";
  57. var expectedMessage = String.Format("who is MediaBrowser{0}?", context);
  58. var expectedMessageBytes = Encoding.UTF8.GetBytes(expectedMessage);
  59. if (expectedMessageBytes.SequenceEqual(e.Bytes))
  60. {
  61. _logger.Info("Received UDP server request from " + e.RemoteEndPoint);
  62. var localAddress = GetLocalIpAddress();
  63. if (!string.IsNullOrEmpty(localAddress))
  64. {
  65. // Send a response back with our ip address and port
  66. var response = String.Format("MediaBrowser{0}|{1}:{2}", context, GetLocalIpAddress(), _serverConfigurationManager.Configuration.HttpServerPortNumber);
  67. await SendAsync(Encoding.UTF8.GetBytes(response), e.RemoteEndPoint);
  68. }
  69. else
  70. {
  71. _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
  72. }
  73. }
  74. }
  75. /// <summary>
  76. /// Gets the local ip address.
  77. /// </summary>
  78. /// <returns>System.String.</returns>
  79. private string GetLocalIpAddress()
  80. {
  81. var localAddresses = _networkManager.GetLocalIpAddresses().ToList();
  82. // Cross-check the local ip addresses with addresses that have been received on with the http server
  83. var matchedAddress = _httpServer.LocalEndPoints
  84. .ToList()
  85. .Select(i => i.Split(':').FirstOrDefault())
  86. .Where(i => !string.IsNullOrEmpty(i))
  87. .FirstOrDefault(i => localAddresses.Contains(i, StringComparer.OrdinalIgnoreCase));
  88. // Return the first matched address, if found, or the first known local address
  89. return matchedAddress ?? localAddresses.FirstOrDefault();
  90. }
  91. /// <summary>
  92. /// The _udp client
  93. /// </summary>
  94. private UdpClient _udpClient;
  95. /// <summary>
  96. /// Starts the specified port.
  97. /// </summary>
  98. /// <param name="port">The port.</param>
  99. public void Start(int port)
  100. {
  101. _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port));
  102. _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  103. Task.Run(() => StartListening());
  104. }
  105. private async void StartListening()
  106. {
  107. while (!_isDisposed)
  108. {
  109. try
  110. {
  111. var result = await GetResult().ConfigureAwait(false);
  112. OnMessageReceived(result);
  113. }
  114. catch (ObjectDisposedException)
  115. {
  116. break;
  117. }
  118. }
  119. }
  120. private Task<UdpReceiveResult> GetResult()
  121. {
  122. try
  123. {
  124. return _udpClient.ReceiveAsync();
  125. }
  126. catch (ObjectDisposedException)
  127. {
  128. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  129. }
  130. catch (Exception ex)
  131. {
  132. _logger.ErrorException("Error receiving udp message", ex);
  133. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  134. }
  135. }
  136. /// <summary>
  137. /// Called when [message received].
  138. /// </summary>
  139. /// <param name="message">The message.</param>
  140. private void OnMessageReceived(UdpReceiveResult message)
  141. {
  142. if (message.RemoteEndPoint.Port == 0)
  143. {
  144. return;
  145. }
  146. var bytes = message.Buffer;
  147. OnMessageReceived(new UdpMessageReceivedEventArgs
  148. {
  149. Bytes = bytes,
  150. RemoteEndPoint = message.RemoteEndPoint.ToString()
  151. });
  152. }
  153. /// <summary>
  154. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  155. /// </summary>
  156. public void Dispose()
  157. {
  158. Dispose(true);
  159. GC.SuppressFinalize(this);
  160. }
  161. /// <summary>
  162. /// Stops this instance.
  163. /// </summary>
  164. public void Stop()
  165. {
  166. _isDisposed = true;
  167. if (_udpClient != null)
  168. {
  169. _udpClient.Close();
  170. }
  171. }
  172. /// <summary>
  173. /// Releases unmanaged and - optionally - managed resources.
  174. /// </summary>
  175. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  176. protected virtual void Dispose(bool dispose)
  177. {
  178. if (dispose)
  179. {
  180. Stop();
  181. }
  182. }
  183. /// <summary>
  184. /// Sends the async.
  185. /// </summary>
  186. /// <param name="data">The data.</param>
  187. /// <param name="ipAddress">The ip address.</param>
  188. /// <param name="port">The port.</param>
  189. /// <returns>Task{System.Int32}.</returns>
  190. /// <exception cref="System.ArgumentNullException">data</exception>
  191. public Task SendAsync(string data, string ipAddress, int port)
  192. {
  193. return SendAsync(Encoding.UTF8.GetBytes(data), ipAddress, port);
  194. }
  195. /// <summary>
  196. /// Sends the async.
  197. /// </summary>
  198. /// <param name="bytes">The bytes.</param>
  199. /// <param name="ipAddress">The ip address.</param>
  200. /// <param name="port">The port.</param>
  201. /// <returns>Task{System.Int32}.</returns>
  202. /// <exception cref="System.ArgumentNullException">bytes</exception>
  203. public Task SendAsync(byte[] bytes, string ipAddress, int port)
  204. {
  205. if (bytes == null)
  206. {
  207. throw new ArgumentNullException("bytes");
  208. }
  209. if (string.IsNullOrEmpty(ipAddress))
  210. {
  211. throw new ArgumentNullException("ipAddress");
  212. }
  213. return _udpClient.SendAsync(bytes, bytes.Length, ipAddress, port);
  214. }
  215. /// <summary>
  216. /// Sends the async.
  217. /// </summary>
  218. /// <param name="bytes">The bytes.</param>
  219. /// <param name="remoteEndPoint">The remote end point.</param>
  220. /// <returns>Task.</returns>
  221. /// <exception cref="System.ArgumentNullException">
  222. /// bytes
  223. /// or
  224. /// remoteEndPoint
  225. /// </exception>
  226. public async Task SendAsync(byte[] bytes, string remoteEndPoint)
  227. {
  228. if (bytes == null)
  229. {
  230. throw new ArgumentNullException("bytes");
  231. }
  232. if (string.IsNullOrEmpty(remoteEndPoint))
  233. {
  234. throw new ArgumentNullException("remoteEndPoint");
  235. }
  236. await _udpClient.SendAsync(bytes, bytes.Length, _networkManager.Parse(remoteEndPoint)).ConfigureAwait(false);
  237. _logger.Info("Udp message sent to {0}", remoteEndPoint);
  238. }
  239. }
  240. }