UdpServer.cs 11 KB

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