2
0

NativeWebSocket.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 (WebSocketException ex)
  74. {
  75. _logger.ErrorException("Error receiving web socket message", ex);
  76. break;
  77. }
  78. if (bytes == null)
  79. {
  80. // Connection closed
  81. break;
  82. }
  83. if (OnReceiveBytes != null)
  84. {
  85. OnReceiveBytes(bytes);
  86. }
  87. }
  88. }
  89. /// <summary>
  90. /// Receives the async.
  91. /// </summary>
  92. /// <param name="cancellationToken">The cancellation token.</param>
  93. /// <returns>Task{WebSocketMessageInfo}.</returns>
  94. /// <exception cref="System.Net.WebSockets.WebSocketException">Connection closed</exception>
  95. private async Task<byte[]> ReceiveBytesAsync(CancellationToken cancellationToken)
  96. {
  97. var bytes = new byte[4096];
  98. var buffer = new ArraySegment<byte>(bytes);
  99. var result = await WebSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
  100. if (result.CloseStatus.HasValue)
  101. {
  102. _logger.Info("Web socket connection closed.");
  103. return null;
  104. }
  105. return buffer.Array;
  106. }
  107. /// <summary>
  108. /// Sends the async.
  109. /// </summary>
  110. /// <param name="bytes">The bytes.</param>
  111. /// <param name="type">The type.</param>
  112. /// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
  113. /// <param name="cancellationToken">The cancellation token.</param>
  114. /// <returns>Task.</returns>
  115. public Task SendAsync(byte[] bytes, WebSocketMessageType type, bool endOfMessage, CancellationToken cancellationToken)
  116. {
  117. System.Net.WebSockets.WebSocketMessageType nativeType;
  118. if (!Enum.TryParse(type.ToString(), true, out nativeType))
  119. {
  120. _logger.Warn("Unrecognized WebSocketMessageType: {0}", type.ToString());
  121. }
  122. return WebSocket.SendAsync(new ArraySegment<byte>(bytes), nativeType, true, cancellationToken);
  123. }
  124. /// <summary>
  125. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  126. /// </summary>
  127. public void Dispose()
  128. {
  129. Dispose(true);
  130. }
  131. /// <summary>
  132. /// Releases unmanaged and - optionally - managed resources.
  133. /// </summary>
  134. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  135. protected virtual void Dispose(bool dispose)
  136. {
  137. if (dispose)
  138. {
  139. WebSocket.Dispose();
  140. }
  141. }
  142. /// <summary>
  143. /// Gets or sets the receive action.
  144. /// </summary>
  145. /// <value>The receive action.</value>
  146. public Action<byte[]> OnReceiveBytes { get; set; }
  147. public Action<string> OnReceive { get; set; }
  148. }
  149. }