UdpServer.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. catch (Exception ex)
  119. {
  120. _logger.ErrorException("Error in StartListening", ex);
  121. }
  122. }
  123. }
  124. private Task<UdpReceiveResult> GetResult()
  125. {
  126. try
  127. {
  128. return _udpClient.ReceiveAsync();
  129. }
  130. catch (ObjectDisposedException)
  131. {
  132. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  133. }
  134. catch (Exception ex)
  135. {
  136. _logger.ErrorException("Error receiving udp message", ex);
  137. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  138. }
  139. }
  140. /// <summary>
  141. /// Called when [message received].
  142. /// </summary>
  143. /// <param name="message">The message.</param>
  144. private void OnMessageReceived(UdpReceiveResult message)
  145. {
  146. if (message.RemoteEndPoint.Port == 0)
  147. {
  148. return;
  149. }
  150. var bytes = message.Buffer;
  151. OnMessageReceived(new UdpMessageReceivedEventArgs
  152. {
  153. Bytes = bytes,
  154. RemoteEndPoint = message.RemoteEndPoint.ToString()
  155. });
  156. }
  157. /// <summary>
  158. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  159. /// </summary>
  160. public void Dispose()
  161. {
  162. Dispose(true);
  163. GC.SuppressFinalize(this);
  164. }
  165. /// <summary>
  166. /// Stops this instance.
  167. /// </summary>
  168. public void Stop()
  169. {
  170. _isDisposed = true;
  171. if (_udpClient != null)
  172. {
  173. _udpClient.Close();
  174. }
  175. }
  176. /// <summary>
  177. /// Releases unmanaged and - optionally - managed resources.
  178. /// </summary>
  179. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  180. protected virtual void Dispose(bool dispose)
  181. {
  182. if (dispose)
  183. {
  184. Stop();
  185. }
  186. }
  187. /// <summary>
  188. /// Sends the async.
  189. /// </summary>
  190. /// <param name="data">The data.</param>
  191. /// <param name="ipAddress">The ip address.</param>
  192. /// <param name="port">The port.</param>
  193. /// <returns>Task{System.Int32}.</returns>
  194. /// <exception cref="System.ArgumentNullException">data</exception>
  195. public Task SendAsync(string data, string ipAddress, int port)
  196. {
  197. return SendAsync(Encoding.UTF8.GetBytes(data), ipAddress, port);
  198. }
  199. /// <summary>
  200. /// Sends the async.
  201. /// </summary>
  202. /// <param name="bytes">The bytes.</param>
  203. /// <param name="ipAddress">The ip address.</param>
  204. /// <param name="port">The port.</param>
  205. /// <returns>Task{System.Int32}.</returns>
  206. /// <exception cref="System.ArgumentNullException">bytes</exception>
  207. public Task SendAsync(byte[] bytes, string ipAddress, int port)
  208. {
  209. if (bytes == null)
  210. {
  211. throw new ArgumentNullException("bytes");
  212. }
  213. if (string.IsNullOrEmpty(ipAddress))
  214. {
  215. throw new ArgumentNullException("ipAddress");
  216. }
  217. return _udpClient.SendAsync(bytes, bytes.Length, ipAddress, port);
  218. }
  219. /// <summary>
  220. /// Sends the async.
  221. /// </summary>
  222. /// <param name="bytes">The bytes.</param>
  223. /// <param name="remoteEndPoint">The remote end point.</param>
  224. /// <returns>Task.</returns>
  225. /// <exception cref="System.ArgumentNullException">
  226. /// bytes
  227. /// or
  228. /// remoteEndPoint
  229. /// </exception>
  230. public async Task SendAsync(byte[] bytes, string remoteEndPoint)
  231. {
  232. if (bytes == null)
  233. {
  234. throw new ArgumentNullException("bytes");
  235. }
  236. if (string.IsNullOrEmpty(remoteEndPoint))
  237. {
  238. throw new ArgumentNullException("remoteEndPoint");
  239. }
  240. await _udpClient.SendAsync(bytes, bytes.Length, _networkManager.Parse(remoteEndPoint)).ConfigureAwait(false);
  241. _logger.Info("Udp message sent to {0}", remoteEndPoint);
  242. }
  243. }
  244. }