NativeWebSocket.cs 7.9 KB

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