SharpWebSocket.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Emby.Server.Implementations.Net;
  6. using Microsoft.Extensions.Logging;
  7. namespace Jellyfin.Server.SocketSharp
  8. {
  9. public class SharpWebSocket : IWebSocket
  10. {
  11. /// <summary>
  12. /// The logger
  13. /// </summary>
  14. private readonly ILogger _logger;
  15. public event EventHandler<EventArgs> Closed;
  16. /// <summary>
  17. /// Gets or sets the web socket.
  18. /// </summary>
  19. /// <value>The web socket.</value>
  20. private SocketHttpListener.WebSocket WebSocket { get; set; }
  21. private TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  22. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  23. private bool _disposed = false;
  24. public SharpWebSocket(SocketHttpListener.WebSocket socket, ILogger logger)
  25. {
  26. if (socket == null)
  27. {
  28. throw new ArgumentNullException(nameof(socket));
  29. }
  30. if (logger == null)
  31. {
  32. throw new ArgumentNullException(nameof(logger));
  33. }
  34. _logger = logger;
  35. WebSocket = socket;
  36. socket.OnMessage += OnSocketMessage;
  37. socket.OnClose += OnSocketClose;
  38. socket.OnError += OnSocketError;
  39. }
  40. public Task ConnectAsServerAsync()
  41. => WebSocket.ConnectAsServer();
  42. public Task StartReceive()
  43. {
  44. return _taskCompletionSource.Task;
  45. }
  46. private void OnSocketError(object sender, SocketHttpListener.ErrorEventArgs e)
  47. {
  48. _logger.LogError("Error in SharpWebSocket: {Message}", e.Message ?? string.Empty);
  49. // Closed?.Invoke(this, EventArgs.Empty);
  50. }
  51. private void OnSocketClose(object sender, SocketHttpListener.CloseEventArgs e)
  52. {
  53. _taskCompletionSource.TrySetResult(true);
  54. Closed?.Invoke(this, EventArgs.Empty);
  55. }
  56. private void OnSocketMessage(object sender, SocketHttpListener.MessageEventArgs e)
  57. {
  58. if (OnReceiveBytes != null)
  59. {
  60. OnReceiveBytes(e.RawData);
  61. }
  62. }
  63. /// <summary>
  64. /// Gets or sets the state.
  65. /// </summary>
  66. /// <value>The state.</value>
  67. public WebSocketState State => WebSocket.ReadyState;
  68. /// <summary>
  69. /// Sends the async.
  70. /// </summary>
  71. /// <param name="bytes">The bytes.</param>
  72. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  73. /// <param name="cancellationToken">The cancellation token.</param>
  74. /// <returns>Task.</returns>
  75. public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
  76. {
  77. return WebSocket.SendAsync(bytes);
  78. }
  79. /// <summary>
  80. /// Sends the asynchronous.
  81. /// </summary>
  82. /// <param name="text">The text.</param>
  83. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <returns>Task.</returns>
  86. public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
  87. {
  88. return WebSocket.SendAsync(text);
  89. }
  90. /// <summary>
  91. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  92. /// </summary>
  93. public void Dispose()
  94. {
  95. Dispose(true);
  96. GC.SuppressFinalize(this);
  97. }
  98. /// <summary>
  99. /// Releases unmanaged and - optionally - managed resources.
  100. /// </summary>
  101. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  102. protected virtual void Dispose(bool dispose)
  103. {
  104. if (_disposed)
  105. {
  106. return;
  107. }
  108. if (dispose)
  109. {
  110. WebSocket.OnMessage -= OnSocketMessage;
  111. WebSocket.OnClose -= OnSocketClose;
  112. WebSocket.OnError -= OnSocketError;
  113. _cancellationTokenSource.Cancel();
  114. WebSocket.CloseAsync().GetAwaiter().GetResult();
  115. }
  116. _disposed = true;
  117. }
  118. /// <summary>
  119. /// Gets or sets the receive action.
  120. /// </summary>
  121. /// <value>The receive action.</value>
  122. public Action<byte[]> OnReceiveBytes { get; set; }
  123. }
  124. }