SharpWebSocket.cs 4.5 KB

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