SharpWebSocket.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. WebSocket.ConnectAsServer();
  40. }
  41. public Task StartReceive()
  42. {
  43. return _taskCompletionSource.Task;
  44. }
  45. private void OnSocketError(object sender, SocketHttpListener.ErrorEventArgs e)
  46. {
  47. _logger.LogError("Error in SharpWebSocket: {Message}", e.Message ?? string.Empty);
  48. // Closed?.Invoke(this, EventArgs.Empty);
  49. }
  50. private void OnSocketClose(object sender, SocketHttpListener.CloseEventArgs e)
  51. {
  52. _taskCompletionSource.TrySetResult(true);
  53. Closed?.Invoke(this, EventArgs.Empty);
  54. }
  55. private void OnSocketMessage(object sender, SocketHttpListener.MessageEventArgs e)
  56. {
  57. if (OnReceiveBytes != null)
  58. {
  59. OnReceiveBytes(e.RawData);
  60. }
  61. }
  62. /// <summary>
  63. /// Gets or sets the state.
  64. /// </summary>
  65. /// <value>The state.</value>
  66. public WebSocketState State => WebSocket.ReadyState;
  67. /// <summary>
  68. /// Sends the async.
  69. /// </summary>
  70. /// <param name="bytes">The bytes.</param>
  71. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  72. /// <param name="cancellationToken">The cancellation token.</param>
  73. /// <returns>Task.</returns>
  74. public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
  75. {
  76. return WebSocket.SendAsync(bytes);
  77. }
  78. /// <summary>
  79. /// Sends the asynchronous.
  80. /// </summary>
  81. /// <param name="text">The text.</param>
  82. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  83. /// <param name="cancellationToken">The cancellation token.</param>
  84. /// <returns>Task.</returns>
  85. public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
  86. {
  87. return WebSocket.SendAsync(text);
  88. }
  89. /// <summary>
  90. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  91. /// </summary>
  92. public void Dispose()
  93. {
  94. Dispose(true);
  95. GC.SuppressFinalize(this);
  96. }
  97. /// <summary>
  98. /// Releases unmanaged and - optionally - managed resources.
  99. /// </summary>
  100. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  101. protected virtual void Dispose(bool dispose)
  102. {
  103. if (_disposed)
  104. {
  105. return;
  106. }
  107. if (dispose)
  108. {
  109. WebSocket.OnMessage -= OnSocketMessage;
  110. WebSocket.OnClose -= OnSocketClose;
  111. WebSocket.OnError -= OnSocketError;
  112. _cancellationTokenSource.Cancel();
  113. WebSocket.Close();
  114. }
  115. _disposed = true;
  116. }
  117. /// <summary>
  118. /// Gets or sets the receive action.
  119. /// </summary>
  120. /// <value>The receive action.</value>
  121. public Action<byte[]> OnReceiveBytes { get; set; }
  122. }
  123. }