UdpServer.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 info = _appHost.GetSystemInfo();
  75. var localAddress = info.LocalAddress;
  76. if (!string.IsNullOrEmpty(localAddress))
  77. {
  78. // This is how we did the old v1 search, so need to strip off the protocol
  79. var index = localAddress.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  80. if (index != -1)
  81. {
  82. localAddress = localAddress.Substring(index + 3);
  83. }
  84. // Send a response back with our ip address and port
  85. var response = String.Format("MediaBrowserServer|{0}", localAddress);
  86. await SendAsync(Encoding.UTF8.GetBytes(response), endpoint);
  87. }
  88. else
  89. {
  90. _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
  91. }
  92. }
  93. private async void RespondToV2Message(string endpoint)
  94. {
  95. var info = _appHost.GetSystemInfo();
  96. if (!string.IsNullOrEmpty(info.LocalAddress))
  97. {
  98. var response = new ServerDiscoveryInfo
  99. {
  100. Address = info.LocalAddress,
  101. Id = info.Id,
  102. Name = info.ServerName
  103. };
  104. await SendAsync(Encoding.UTF8.GetBytes(_json.SerializeToString(response)), endpoint);
  105. }
  106. else
  107. {
  108. _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
  109. }
  110. }
  111. /// <summary>
  112. /// The _udp client
  113. /// </summary>
  114. private UdpClient _udpClient;
  115. /// <summary>
  116. /// Starts the specified port.
  117. /// </summary>
  118. /// <param name="port">The port.</param>
  119. public void Start(int port)
  120. {
  121. _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port));
  122. _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  123. Task.Run(() => StartListening());
  124. }
  125. private async void StartListening()
  126. {
  127. while (!_isDisposed)
  128. {
  129. try
  130. {
  131. var result = await GetResult().ConfigureAwait(false);
  132. OnMessageReceived(result);
  133. }
  134. catch (ObjectDisposedException)
  135. {
  136. break;
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.ErrorException("Error in StartListening", ex);
  141. }
  142. }
  143. }
  144. private Task<UdpReceiveResult> GetResult()
  145. {
  146. try
  147. {
  148. return _udpClient.ReceiveAsync();
  149. }
  150. catch (ObjectDisposedException)
  151. {
  152. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  153. }
  154. catch (Exception ex)
  155. {
  156. _logger.ErrorException("Error receiving udp message", ex);
  157. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  158. }
  159. }
  160. /// <summary>
  161. /// Called when [message received].
  162. /// </summary>
  163. /// <param name="message">The message.</param>
  164. private void OnMessageReceived(UdpReceiveResult message)
  165. {
  166. if (message.RemoteEndPoint.Port == 0)
  167. {
  168. return;
  169. }
  170. var bytes = message.Buffer;
  171. OnMessageReceived(new UdpMessageReceivedEventArgs
  172. {
  173. Bytes = bytes,
  174. RemoteEndPoint = message.RemoteEndPoint.ToString()
  175. });
  176. }
  177. /// <summary>
  178. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  179. /// </summary>
  180. public void Dispose()
  181. {
  182. Dispose(true);
  183. GC.SuppressFinalize(this);
  184. }
  185. /// <summary>
  186. /// Stops this instance.
  187. /// </summary>
  188. public void Stop()
  189. {
  190. _isDisposed = true;
  191. if (_udpClient != null)
  192. {
  193. _udpClient.Close();
  194. }
  195. }
  196. /// <summary>
  197. /// Releases unmanaged and - optionally - managed resources.
  198. /// </summary>
  199. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  200. protected virtual void Dispose(bool dispose)
  201. {
  202. if (dispose)
  203. {
  204. Stop();
  205. }
  206. }
  207. /// <summary>
  208. /// Sends the async.
  209. /// </summary>
  210. /// <param name="data">The data.</param>
  211. /// <param name="ipAddress">The ip address.</param>
  212. /// <param name="port">The port.</param>
  213. /// <returns>Task{System.Int32}.</returns>
  214. /// <exception cref="System.ArgumentNullException">data</exception>
  215. public Task SendAsync(string data, string ipAddress, int port)
  216. {
  217. return SendAsync(Encoding.UTF8.GetBytes(data), ipAddress, port);
  218. }
  219. /// <summary>
  220. /// Sends the async.
  221. /// </summary>
  222. /// <param name="bytes">The bytes.</param>
  223. /// <param name="ipAddress">The ip address.</param>
  224. /// <param name="port">The port.</param>
  225. /// <returns>Task{System.Int32}.</returns>
  226. /// <exception cref="System.ArgumentNullException">bytes</exception>
  227. public Task SendAsync(byte[] bytes, string ipAddress, int port)
  228. {
  229. if (bytes == null)
  230. {
  231. throw new ArgumentNullException("bytes");
  232. }
  233. if (string.IsNullOrEmpty(ipAddress))
  234. {
  235. throw new ArgumentNullException("ipAddress");
  236. }
  237. return _udpClient.SendAsync(bytes, bytes.Length, ipAddress, port);
  238. }
  239. /// <summary>
  240. /// Sends the async.
  241. /// </summary>
  242. /// <param name="bytes">The bytes.</param>
  243. /// <param name="remoteEndPoint">The remote end point.</param>
  244. /// <returns>Task.</returns>
  245. /// <exception cref="System.ArgumentNullException">
  246. /// bytes
  247. /// or
  248. /// remoteEndPoint
  249. /// </exception>
  250. public async Task SendAsync(byte[] bytes, string remoteEndPoint)
  251. {
  252. if (bytes == null)
  253. {
  254. throw new ArgumentNullException("bytes");
  255. }
  256. if (string.IsNullOrEmpty(remoteEndPoint))
  257. {
  258. throw new ArgumentNullException("remoteEndPoint");
  259. }
  260. try
  261. {
  262. await _udpClient.SendAsync(bytes, bytes.Length, _networkManager.Parse(remoteEndPoint)).ConfigureAwait(false);
  263. _logger.Info("Udp message sent to {0}", remoteEndPoint);
  264. }
  265. catch (Exception ex)
  266. {
  267. _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint);
  268. }
  269. }
  270. }
  271. }