UdpServerEntryPoint.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #nullable enable
  2. using System.Net.Sockets;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Emby.Server.Implementations.Udp;
  6. using MediaBrowser.Controller;
  7. using MediaBrowser.Controller.Plugins;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.Logging;
  10. namespace Emby.Server.Implementations.EntryPoints
  11. {
  12. /// <summary>
  13. /// Class UdpServerEntryPoint.
  14. /// </summary>
  15. public sealed class UdpServerEntryPoint : IServerEntryPoint
  16. {
  17. /// <summary>
  18. /// The port of the UDP server.
  19. /// </summary>
  20. public const int PortNumber = 7359;
  21. /// <summary>
  22. /// The logger.
  23. /// </summary>
  24. private readonly ILogger<UdpServerEntryPoint> _logger;
  25. private readonly IServerApplicationHost _appHost;
  26. private readonly IConfiguration _config;
  27. /// <summary>
  28. /// The UDP server.
  29. /// </summary>
  30. private UdpServer? _udpServer;
  31. private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  32. private bool _disposed = false;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="UdpServerEntryPoint" /> class.
  35. /// </summary>
  36. public UdpServerEntryPoint(
  37. ILogger<UdpServerEntryPoint> logger,
  38. IServerApplicationHost appHost,
  39. IConfiguration configuration)
  40. {
  41. _logger = logger;
  42. _appHost = appHost;
  43. _config = configuration;
  44. }
  45. /// <inheritdoc />
  46. public Task RunAsync()
  47. {
  48. try
  49. {
  50. _udpServer = new UdpServer(_logger, _appHost, _config);
  51. _udpServer.Start(PortNumber, _cancellationTokenSource.Token);
  52. }
  53. catch (SocketException ex)
  54. {
  55. _logger.LogWarning(ex, "Unable to start AutoDiscovery listener on UDP port {PortNumber}", PortNumber);
  56. }
  57. return Task.CompletedTask;
  58. }
  59. /// <inheritdoc />
  60. public void Dispose()
  61. {
  62. if (_disposed)
  63. {
  64. return;
  65. }
  66. _cancellationTokenSource.Cancel();
  67. _cancellationTokenSource.Dispose();
  68. _udpServer?.Dispose();
  69. _udpServer = null;
  70. _disposed = true;
  71. }
  72. }
  73. }