SharpWebSocket.cs 5.6 KB

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