SharpWebSocket.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. 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 (OnReceiveBytes != null)
  57. {
  58. OnReceiveBytes(e.RawData);
  59. }
  60. }
  61. /// <summary>
  62. /// Gets or sets the state.
  63. /// </summary>
  64. /// <value>The state.</value>
  65. public WebSocketState State => WebSocket.ReadyState;
  66. /// <summary>
  67. /// Sends the async.
  68. /// </summary>
  69. /// <param name="bytes">The bytes.</param>
  70. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  71. /// <param name="cancellationToken">The cancellation token.</param>
  72. /// <returns>Task.</returns>
  73. public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
  74. {
  75. return WebSocket.SendAsync(bytes);
  76. }
  77. /// <summary>
  78. /// Sends the asynchronous.
  79. /// </summary>
  80. /// <param name="text">The text.</param>
  81. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  82. /// <param name="cancellationToken">The cancellation token.</param>
  83. /// <returns>Task.</returns>
  84. public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
  85. {
  86. return WebSocket.SendAsync(text);
  87. }
  88. /// <summary>
  89. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  90. /// </summary>
  91. public void Dispose()
  92. {
  93. Dispose(true);
  94. }
  95. /// <summary>
  96. /// Releases unmanaged and - optionally - managed resources.
  97. /// </summary>
  98. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  99. protected virtual void Dispose(bool dispose)
  100. {
  101. if (dispose)
  102. {
  103. WebSocket.OnMessage -= socket_OnMessage;
  104. WebSocket.OnClose -= socket_OnClose;
  105. WebSocket.OnError -= socket_OnError;
  106. _cancellationTokenSource.Cancel();
  107. WebSocket.Close();
  108. }
  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. }