UdpServer.cs 9.5 KB

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