UdpServerEntryPoint.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. /// <param name="logger">Instance of the <see cref="ILogger{UdpServerEntryPoint}"/> interface.</param>
  37. /// <param name="appHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
  38. /// <param name="configuration">Instance of the <see cref="IConfiguration"/> interface.</param>
  39. public UdpServerEntryPoint(
  40. ILogger<UdpServerEntryPoint> logger,
  41. IServerApplicationHost appHost,
  42. IConfiguration configuration)
  43. {
  44. _logger = logger;
  45. _appHost = appHost;
  46. _config = configuration;
  47. }
  48. /// <inheritdoc />
  49. public Task RunAsync()
  50. {
  51. CheckDisposed();
  52. try
  53. {
  54. _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber);
  55. _udpServer.Start(_cancellationTokenSource.Token);
  56. }
  57. catch (SocketException ex)
  58. {
  59. _logger.LogWarning(ex, "Unable to start AutoDiscovery listener on UDP port {PortNumber}", PortNumber);
  60. }
  61. return Task.CompletedTask;
  62. }
  63. private void CheckDisposed()
  64. {
  65. if (_disposed)
  66. {
  67. throw new ObjectDisposedException(this.GetType().Name);
  68. }
  69. }
  70. /// <inheritdoc />
  71. public void Dispose()
  72. {
  73. if (_disposed)
  74. {
  75. return;
  76. }
  77. _cancellationTokenSource.Cancel();
  78. _cancellationTokenSource.Dispose();
  79. _udpServer?.Dispose();
  80. _udpServer = null;
  81. _disposed = true;
  82. }
  83. }
  84. }