UdpServer.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Text.Json;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Model.ApiClient;
  10. using Microsoft.Extensions.Logging;
  11. namespace Emby.Server.Implementations.Udp
  12. {
  13. /// <summary>
  14. /// Provides a Udp Server.
  15. /// </summary>
  16. public sealed class UdpServer : IDisposable
  17. {
  18. /// <summary>
  19. /// The _logger
  20. /// </summary>
  21. private readonly ILogger _logger;
  22. private readonly IServerApplicationHost _appHost;
  23. private Socket _udpSocket;
  24. private IPEndPoint _endpoint;
  25. private readonly byte[] _receiveBuffer = new byte[8192];
  26. private bool _disposed = false;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="UdpServer" /> class.
  29. /// </summary>
  30. public UdpServer(ILogger logger, IServerApplicationHost appHost)
  31. {
  32. _logger = logger;
  33. _appHost = appHost;
  34. }
  35. private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken)
  36. {
  37. var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  38. if (!string.IsNullOrEmpty(localUrl))
  39. {
  40. var response = new ServerDiscoveryInfo
  41. {
  42. Address = localUrl,
  43. Id = _appHost.SystemId,
  44. Name = _appHost.FriendlyName
  45. };
  46. try
  47. {
  48. await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
  49. }
  50. catch (SocketException ex)
  51. {
  52. _logger.LogError(ex, "Error sending response message");
  53. }
  54. var parts = messageText.Split('|');
  55. if (parts.Length > 1)
  56. {
  57. _appHost.EnableLoopback(parts[1]);
  58. }
  59. }
  60. else
  61. {
  62. _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
  63. }
  64. }
  65. /// <summary>
  66. /// Starts the specified port.
  67. /// </summary>
  68. /// <param name="port">The port.</param>
  69. /// <param name="cancellationToken"></param>
  70. public void Start(int port, CancellationToken cancellationToken)
  71. {
  72. _endpoint = new IPEndPoint(IPAddress.Any, port);
  73. _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  74. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  75. _udpSocket.Bind(_endpoint);
  76. _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
  77. }
  78. private async Task BeginReceiveAsync(CancellationToken cancellationToken)
  79. {
  80. while (!cancellationToken.IsCancellationRequested)
  81. {
  82. try
  83. {
  84. var result = await _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint).ConfigureAwait(false);
  85. cancellationToken.ThrowIfCancellationRequested();
  86. var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
  87. if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
  88. {
  89. await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
  90. }
  91. }
  92. catch (SocketException ex)
  93. {
  94. _logger.LogError(ex, "Failed to receive data drom socket");
  95. }
  96. catch (OperationCanceledException)
  97. {
  98. // Don't throw
  99. }
  100. }
  101. }
  102. /// <inheritdoc />
  103. public void Dispose()
  104. {
  105. if (_disposed)
  106. {
  107. return;
  108. }
  109. _udpSocket?.Dispose();
  110. GC.SuppressFinalize(this);
  111. }
  112. }
  113. }