WebSocketConnection.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. private bool _disposed = false;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  37. /// </summary>
  38. /// <param name="logger">The logger.</param>
  39. /// <param name="socket">The socket.</param>
  40. /// <param name="remoteEndPoint">The remote end point.</param>
  41. /// <param name="query">The query.</param>
  42. public WebSocketConnection(
  43. ILogger<WebSocketConnection> logger,
  44. WebSocket socket,
  45. IPAddress? remoteEndPoint,
  46. IQueryCollection query)
  47. {
  48. _logger = logger;
  49. _socket = socket;
  50. RemoteEndPoint = remoteEndPoint;
  51. QueryString = query;
  52. _jsonOptions = JsonDefaults.GetOptions();
  53. LastActivityDate = DateTime.Now;
  54. }
  55. /// <inheritdoc />
  56. public event EventHandler<EventArgs>? Closed;
  57. /// <summary>
  58. /// Gets or sets the remote end point.
  59. /// </summary>
  60. public IPAddress? RemoteEndPoint { get; }
  61. /// <summary>
  62. /// Gets or sets the receive action.
  63. /// </summary>
  64. /// <value>The receive action.</value>
  65. public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
  66. /// <summary>
  67. /// Gets the last activity date.
  68. /// </summary>
  69. /// <value>The last activity date.</value>
  70. public DateTime LastActivityDate { get; private set; }
  71. /// <summary>
  72. /// Gets or sets the query string.
  73. /// </summary>
  74. /// <value>The query string.</value>
  75. public IQueryCollection QueryString { get; }
  76. /// <summary>
  77. /// Gets the state.
  78. /// </summary>
  79. /// <value>The state.</value>
  80. public WebSocketState State => _socket.State;
  81. /// <summary>
  82. /// Sends a message asynchronously.
  83. /// </summary>
  84. /// <typeparam name="T"></typeparam>
  85. /// <param name="message">The message.</param>
  86. /// <param name="cancellationToken">The cancellation token.</param>
  87. /// <returns>Task.</returns>
  88. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  89. {
  90. var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
  91. return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
  92. }
  93. /// <inheritdoc />
  94. public async Task ProcessAsync(CancellationToken cancellationToken = default)
  95. {
  96. var pipe = new Pipe();
  97. var writer = pipe.Writer;
  98. ValueWebSocketReceiveResult receiveresult;
  99. do
  100. {
  101. // Allocate at least 512 bytes from the PipeWriter
  102. Memory<byte> memory = writer.GetMemory(512);
  103. receiveresult = await _socket.ReceiveAsync(memory, cancellationToken);
  104. int bytesRead = receiveresult.Count;
  105. if (bytesRead == 0)
  106. {
  107. break;
  108. }
  109. // Tell the PipeWriter how much was read from the Socket
  110. writer.Advance(bytesRead);
  111. // Make the data available to the PipeReader
  112. FlushResult flushResult = await writer.FlushAsync();
  113. if (flushResult.IsCompleted)
  114. {
  115. // The PipeReader stopped reading
  116. break;
  117. }
  118. LastActivityDate = DateTime.UtcNow;
  119. if (receiveresult.EndOfMessage)
  120. {
  121. await ProcessInternal(pipe.Reader).ConfigureAwait(false);
  122. }
  123. } while (_socket.State == WebSocketState.Open && receiveresult.MessageType != WebSocketMessageType.Close);
  124. Closed?.Invoke(this, EventArgs.Empty);
  125. await _socket.CloseAsync(
  126. WebSocketCloseStatus.NormalClosure,
  127. string.Empty,
  128. cancellationToken).ConfigureAwait(false);
  129. }
  130. private async Task ProcessInternal(PipeReader reader)
  131. {
  132. ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
  133. ReadOnlySequence<byte> buffer = result.Buffer;
  134. if (OnReceive == null)
  135. {
  136. // Tell the PipeReader how much of the buffer we have consumed
  137. reader.AdvanceTo(buffer.End);
  138. return;
  139. }
  140. WebSocketMessage<object> stub;
  141. try
  142. {
  143. if (buffer.IsSingleSegment)
  144. {
  145. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buffer.FirstSpan, _jsonOptions);
  146. }
  147. else
  148. {
  149. var buf = ArrayPool<byte>.Shared.Rent(Convert.ToInt32(buffer.Length));
  150. try
  151. {
  152. buffer.CopyTo(buf);
  153. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buf, _jsonOptions);
  154. }
  155. finally
  156. {
  157. ArrayPool<byte>.Shared.Return(buf);
  158. }
  159. }
  160. }
  161. catch (JsonException ex)
  162. {
  163. // Tell the PipeReader how much of the buffer we have consumed
  164. reader.AdvanceTo(buffer.End);
  165. _logger.LogError(ex, "Error processing web socket message");
  166. return;
  167. }
  168. // Tell the PipeReader how much of the buffer we have consumed
  169. reader.AdvanceTo(buffer.End);
  170. _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
  171. var info = new WebSocketMessageInfo
  172. {
  173. MessageType = stub.MessageType,
  174. Data = stub.Data?.ToString(), // Data can be null
  175. Connection = this
  176. };
  177. _logger.LogDebug("WS {IP} message info: {@MessageInfo}", RemoteEndPoint, info);
  178. await OnReceive(info).ConfigureAwait(false);
  179. // Stop reading if there's no more data coming
  180. if (result.IsCompleted)
  181. {
  182. return;
  183. }
  184. }
  185. }
  186. }