UdpServerEntryPoint.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  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. CheckDisposed();
  49. try
  50. {
  51. _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber);
  52. _udpServer.Start(_cancellationTokenSource.Token);
  53. }
  54. catch (SocketException ex)
  55. {
  56. _logger.LogWarning(ex, "Unable to start AutoDiscovery listener on UDP port {PortNumber}", PortNumber);
  57. }
  58. return Task.CompletedTask;
  59. }
  60. private void CheckDisposed()
  61. {
  62. if (_disposed)
  63. {
  64. throw new ObjectDisposedException(this.GetType().Name);
  65. }
  66. }
  67. /// <inheritdoc />
  68. public void Dispose()
  69. {
  70. if (_disposed)
  71. {
  72. return;
  73. }
  74. _cancellationTokenSource.Cancel();
  75. _cancellationTokenSource.Dispose();
  76. _udpServer?.Dispose();
  77. _udpServer = null;
  78. _disposed = true;
  79. }
  80. }
  81. }