SharpWebSocket.cs 5.6 KB

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