2
0

NativeWebSocket.cs 5.7 KB

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