NativeWebSocket.cs 7.1 KB

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