NativeWebSocket.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Model.Logging;
  3. using System;
  4. using System.Net.WebSockets;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using WebSocketMessageType = MediaBrowser.Model.Net.WebSocketMessageType;
  8. using WebSocketState = MediaBrowser.Model.Net.WebSocketState;
  9. namespace MediaBrowser.Server.Implementations.HttpServer
  10. {
  11. /// <summary>
  12. /// Class NativeWebSocket
  13. /// </summary>
  14. public class NativeWebSocket : IWebSocket
  15. {
  16. /// <summary>
  17. /// The logger
  18. /// </summary>
  19. private readonly ILogger _logger;
  20. /// <summary>
  21. /// Gets or sets the web socket.
  22. /// </summary>
  23. /// <value>The web socket.</value>
  24. private System.Net.WebSockets.WebSocket WebSocket { get; set; }
  25. private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="NativeWebSocket" /> class.
  28. /// </summary>
  29. /// <param name="socket">The socket.</param>
  30. /// <param name="logger">The logger.</param>
  31. /// <exception cref="System.ArgumentNullException">socket</exception>
  32. public NativeWebSocket(System.Net.WebSockets.WebSocket socket, ILogger logger)
  33. {
  34. if (socket == null)
  35. {
  36. throw new ArgumentNullException("socket");
  37. }
  38. if (logger == null)
  39. {
  40. throw new ArgumentNullException("logger");
  41. }
  42. _logger = logger;
  43. WebSocket = socket;
  44. Receive();
  45. }
  46. /// <summary>
  47. /// Gets or sets the state.
  48. /// </summary>
  49. /// <value>The state.</value>
  50. public WebSocketState State
  51. {
  52. get
  53. {
  54. WebSocketState commonState;
  55. if (!Enum.TryParse(WebSocket.State.ToString(), true, out commonState))
  56. {
  57. _logger.Warn("Unrecognized WebSocketState: {0}", WebSocket.State.ToString());
  58. }
  59. return commonState;
  60. }
  61. }
  62. /// <summary>
  63. /// Receives this instance.
  64. /// </summary>
  65. private async void Receive()
  66. {
  67. while (true)
  68. {
  69. byte[] bytes;
  70. try
  71. {
  72. bytes = await ReceiveBytesAsync(_cancellationTokenSource.Token).ConfigureAwait(false);
  73. }
  74. catch (OperationCanceledException)
  75. {
  76. break;
  77. }
  78. catch (WebSocketException ex)
  79. {
  80. _logger.ErrorException("Error receiving web socket message", ex);
  81. break;
  82. }
  83. if (bytes == null)
  84. {
  85. // Connection closed
  86. break;
  87. }
  88. if (OnReceiveBytes != null)
  89. {
  90. OnReceiveBytes(bytes);
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// Receives the async.
  96. /// </summary>
  97. /// <param name="cancellationToken">The cancellation token.</param>
  98. /// <returns>Task{WebSocketMessageInfo}.</returns>
  99. /// <exception cref="System.Net.WebSockets.WebSocketException">Connection closed</exception>
  100. private async Task<byte[]> ReceiveBytesAsync(CancellationToken cancellationToken)
  101. {
  102. var bytes = new byte[4096];
  103. var buffer = new ArraySegment<byte>(bytes);
  104. var result = await WebSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
  105. if (result.CloseStatus.HasValue)
  106. {
  107. _logger.Info("Web socket connection closed by client.");
  108. return null;
  109. }
  110. return buffer.Array;
  111. }
  112. /// <summary>
  113. /// Sends the async.
  114. /// </summary>
  115. /// <param name="bytes">The bytes.</param>
  116. /// <param name="type">The type.</param>
  117. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  118. /// <param name="cancellationToken">The cancellation token.</param>
  119. /// <returns>Task.</returns>
  120. public Task SendAsync(byte[] bytes, WebSocketMessageType type, bool endOfMessage, CancellationToken cancellationToken)
  121. {
  122. System.Net.WebSockets.WebSocketMessageType nativeType;
  123. if (!Enum.TryParse(type.ToString(), true, out nativeType))
  124. {
  125. _logger.Warn("Unrecognized WebSocketMessageType: {0}", type.ToString());
  126. }
  127. var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token);
  128. return WebSocket.SendAsync(new ArraySegment<byte>(bytes), nativeType, true, linkedTokenSource.Token);
  129. }
  130. /// <summary>
  131. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  132. /// </summary>
  133. public void Dispose()
  134. {
  135. Dispose(true);
  136. }
  137. /// <summary>
  138. /// Releases unmanaged and - optionally - managed resources.
  139. /// </summary>
  140. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  141. protected virtual void Dispose(bool dispose)
  142. {
  143. if (dispose)
  144. {
  145. _cancellationTokenSource.Cancel();
  146. _cancellationTokenSource.Dispose();
  147. WebSocket.Dispose();
  148. }
  149. }
  150. /// <summary>
  151. /// Gets or sets the receive action.
  152. /// </summary>
  153. /// <value>The receive action.</value>
  154. public Action<byte[]> OnReceiveBytes { get; set; }
  155. /// <summary>
  156. /// Gets or sets the on receive.
  157. /// </summary>
  158. /// <value>The on receive.</value>
  159. public Action<string> OnReceive { get; set; }
  160. }
  161. }