NativeWebSocket.cs 5.2 KB

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