SharpWebSocket.cs 4.8 KB

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