UdpServerEntryPoint.cs 2.5 KB

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