SharpWebSocket.cs 4.9 KB

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