SharpWebSocket.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  49. }
  50. void socket_OnClose(object sender, SocketHttpListener.CloseEventArgs e)
  51. {
  52. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  53. }
  54. void socket_OnMessage(object sender, SocketHttpListener.MessageEventArgs e)
  55. {
  56. //if (!string.IsNullOrWhiteSpace(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
  74. {
  75. get
  76. {
  77. WebSocketState commonState;
  78. if (!Enum.TryParse(WebSocket.ReadyState.ToString(), true, out commonState))
  79. {
  80. _logger.Warn("Unrecognized WebSocketState: {0}", WebSocket.ReadyState.ToString());
  81. }
  82. return commonState;
  83. }
  84. }
  85. /// <summary>
  86. /// Sends the async.
  87. /// </summary>
  88. /// <param name="bytes">The bytes.</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(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
  93. {
  94. var completionSource = new TaskCompletionSource<bool>();
  95. WebSocket.SendAsync(bytes, res => completionSource.TrySetResult(true));
  96. return completionSource.Task;
  97. }
  98. /// <summary>
  99. /// Sends the asynchronous.
  100. /// </summary>
  101. /// <param name="text">The text.</param>
  102. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  103. /// <param name="cancellationToken">The cancellation token.</param>
  104. /// <returns>Task.</returns>
  105. public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
  106. {
  107. var completionSource = new TaskCompletionSource<bool>();
  108. WebSocket.SendAsync(text, res => completionSource.TrySetResult(true));
  109. return completionSource.Task;
  110. }
  111. /// <summary>
  112. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  113. /// </summary>
  114. public void Dispose()
  115. {
  116. Dispose(true);
  117. }
  118. /// <summary>
  119. /// Releases unmanaged and - optionally - managed resources.
  120. /// </summary>
  121. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  122. protected virtual void Dispose(bool dispose)
  123. {
  124. if (dispose)
  125. {
  126. WebSocket.OnMessage -= socket_OnMessage;
  127. WebSocket.OnClose -= socket_OnClose;
  128. WebSocket.OnError -= socket_OnError;
  129. _cancellationTokenSource.Cancel();
  130. WebSocket.Close();
  131. }
  132. }
  133. /// <summary>
  134. /// Gets or sets the receive action.
  135. /// </summary>
  136. /// <value>The receive action.</value>
  137. public Action<byte[]> OnReceiveBytes { get; set; }
  138. /// <summary>
  139. /// Gets or sets the on receive.
  140. /// </summary>
  141. /// <value>The on receive.</value>
  142. public Action<string> OnReceive { get; set; }
  143. }
  144. }