WebSocketConnection.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #nullable enable
  2. using System;
  3. using System.Buffers;
  4. using System.IO.Pipelines;
  5. using System.Net;
  6. using System.Net.WebSockets;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Json;
  11. using MediaBrowser.Controller.Net;
  12. using MediaBrowser.Model.Net;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Server.Implementations.HttpServer
  16. {
  17. /// <summary>
  18. /// Class WebSocketConnection.
  19. /// </summary>
  20. public class WebSocketConnection : IWebSocketConnection
  21. {
  22. /// <summary>
  23. /// The logger.
  24. /// </summary>
  25. private readonly ILogger _logger;
  26. /// <summary>
  27. /// The json serializer options.
  28. /// </summary>
  29. private readonly JsonSerializerOptions _jsonOptions;
  30. /// <summary>
  31. /// The socket.
  32. /// </summary>
  33. private readonly WebSocket _socket;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  36. /// </summary>
  37. /// <param name="logger">The logger.</param>
  38. /// <param name="socket">The socket.</param>
  39. /// <param name="remoteEndPoint">The remote end point.</param>
  40. /// <param name="query">The query.</param>
  41. public WebSocketConnection(
  42. ILogger<WebSocketConnection> logger,
  43. WebSocket socket,
  44. IPAddress? remoteEndPoint,
  45. IQueryCollection query)
  46. {
  47. _logger = logger;
  48. _socket = socket;
  49. RemoteEndPoint = remoteEndPoint;
  50. QueryString = query;
  51. _jsonOptions = JsonDefaults.GetOptions();
  52. LastActivityDate = DateTime.Now;
  53. }
  54. /// <inheritdoc />
  55. public event EventHandler<EventArgs>? Closed;
  56. /// <summary>
  57. /// Gets or sets the remote end point.
  58. /// </summary>
  59. public IPAddress? RemoteEndPoint { get; }
  60. /// <summary>
  61. /// Gets or sets the receive action.
  62. /// </summary>
  63. /// <value>The receive action.</value>
  64. public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
  65. /// <summary>
  66. /// Gets the last activity date.
  67. /// </summary>
  68. /// <value>The last activity date.</value>
  69. public DateTime LastActivityDate { get; private set; }
  70. /// <summary>
  71. /// Gets or sets the query string.
  72. /// </summary>
  73. /// <value>The query string.</value>
  74. public IQueryCollection QueryString { get; }
  75. /// <summary>
  76. /// Gets the state.
  77. /// </summary>
  78. /// <value>The state.</value>
  79. public WebSocketState State => _socket.State;
  80. /// <summary>
  81. /// Sends a message asynchronously.
  82. /// </summary>
  83. /// <typeparam name="T"></typeparam>
  84. /// <param name="message">The message.</param>
  85. /// <param name="cancellationToken">The cancellation token.</param>
  86. /// <returns>Task.</returns>
  87. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  88. {
  89. var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
  90. return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
  91. }
  92. /// <inheritdoc />
  93. public async Task ProcessAsync(CancellationToken cancellationToken = default)
  94. {
  95. var pipe = new Pipe();
  96. var writer = pipe.Writer;
  97. ValueWebSocketReceiveResult receiveresult;
  98. do
  99. {
  100. // Allocate at least 512 bytes from the PipeWriter
  101. Memory<byte> memory = writer.GetMemory(512);
  102. try
  103. {
  104. receiveresult = await _socket.ReceiveAsync(memory, cancellationToken);
  105. }
  106. catch (WebSocketException ex)
  107. {
  108. _logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
  109. break;
  110. }
  111. int bytesRead = receiveresult.Count;
  112. if (bytesRead == 0)
  113. {
  114. break;
  115. }
  116. // Tell the PipeWriter how much was read from the Socket
  117. writer.Advance(bytesRead);
  118. // Make the data available to the PipeReader
  119. FlushResult flushResult = await writer.FlushAsync();
  120. if (flushResult.IsCompleted)
  121. {
  122. // The PipeReader stopped reading
  123. break;
  124. }
  125. LastActivityDate = DateTime.UtcNow;
  126. if (receiveresult.EndOfMessage)
  127. {
  128. await ProcessInternal(pipe.Reader).ConfigureAwait(false);
  129. }
  130. } while (
  131. (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
  132. && receiveresult.MessageType != WebSocketMessageType.Close);
  133. Closed?.Invoke(this, EventArgs.Empty);
  134. if (_socket.State == WebSocketState.Open
  135. || _socket.State == WebSocketState.CloseReceived
  136. || _socket.State == WebSocketState.CloseSent)
  137. {
  138. await _socket.CloseAsync(
  139. WebSocketCloseStatus.NormalClosure,
  140. string.Empty,
  141. cancellationToken).ConfigureAwait(false);
  142. }
  143. }
  144. private async Task ProcessInternal(PipeReader reader)
  145. {
  146. ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
  147. ReadOnlySequence<byte> buffer = result.Buffer;
  148. if (OnReceive == null)
  149. {
  150. // Tell the PipeReader how much of the buffer we have consumed
  151. reader.AdvanceTo(buffer.End);
  152. return;
  153. }
  154. WebSocketMessage<object> stub;
  155. try
  156. {
  157. if (buffer.IsSingleSegment)
  158. {
  159. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buffer.FirstSpan, _jsonOptions);
  160. }
  161. else
  162. {
  163. var buf = ArrayPool<byte>.Shared.Rent(Convert.ToInt32(buffer.Length));
  164. try
  165. {
  166. buffer.CopyTo(buf);
  167. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buf, _jsonOptions);
  168. }
  169. finally
  170. {
  171. ArrayPool<byte>.Shared.Return(buf);
  172. }
  173. }
  174. }
  175. catch (JsonException ex)
  176. {
  177. // Tell the PipeReader how much of the buffer we have consumed
  178. reader.AdvanceTo(buffer.End);
  179. _logger.LogError(ex, "Error processing web socket message");
  180. return;
  181. }
  182. // Tell the PipeReader how much of the buffer we have consumed
  183. reader.AdvanceTo(buffer.End);
  184. _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
  185. var info = new WebSocketMessageInfo
  186. {
  187. MessageType = stub.MessageType,
  188. Data = stub.Data?.ToString(), // Data can be null
  189. Connection = this
  190. };
  191. await OnReceive(info).ConfigureAwait(false);
  192. }
  193. }
  194. }