UdpServer.cs 9.9 KB

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