UdpServer.cs 9.7 KB

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