WebSocketConnection.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. try
  104. {
  105. receiveresult = await _socket.ReceiveAsync(memory, cancellationToken);
  106. }
  107. catch (WebSocketException ex)
  108. {
  109. _logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
  110. break;
  111. }
  112. int bytesRead = receiveresult.Count;
  113. if (bytesRead == 0)
  114. {
  115. break;
  116. }
  117. // Tell the PipeWriter how much was read from the Socket
  118. writer.Advance(bytesRead);
  119. // Make the data available to the PipeReader
  120. FlushResult flushResult = await writer.FlushAsync();
  121. if (flushResult.IsCompleted)
  122. {
  123. // The PipeReader stopped reading
  124. break;
  125. }
  126. LastActivityDate = DateTime.UtcNow;
  127. if (receiveresult.EndOfMessage)
  128. {
  129. await ProcessInternal(pipe.Reader).ConfigureAwait(false);
  130. }
  131. } while (
  132. (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
  133. && receiveresult.MessageType != WebSocketMessageType.Close);
  134. Closed?.Invoke(this, EventArgs.Empty);
  135. if (_socket.State == WebSocketState.Open
  136. || _socket.State == WebSocketState.CloseReceived
  137. || _socket.State == WebSocketState.CloseSent)
  138. {
  139. await _socket.CloseAsync(
  140. WebSocketCloseStatus.NormalClosure,
  141. string.Empty,
  142. cancellationToken).ConfigureAwait(false);
  143. }
  144. }
  145. private async Task ProcessInternal(PipeReader reader)
  146. {
  147. ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
  148. ReadOnlySequence<byte> buffer = result.Buffer;
  149. if (OnReceive == null)
  150. {
  151. // Tell the PipeReader how much of the buffer we have consumed
  152. reader.AdvanceTo(buffer.End);
  153. return;
  154. }
  155. WebSocketMessage<object> stub;
  156. try
  157. {
  158. if (buffer.IsSingleSegment)
  159. {
  160. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buffer.FirstSpan, _jsonOptions);
  161. }
  162. else
  163. {
  164. var buf = ArrayPool<byte>.Shared.Rent(Convert.ToInt32(buffer.Length));
  165. try
  166. {
  167. buffer.CopyTo(buf);
  168. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buf, _jsonOptions);
  169. }
  170. finally
  171. {
  172. ArrayPool<byte>.Shared.Return(buf);
  173. }
  174. }
  175. }
  176. catch (JsonException ex)
  177. {
  178. // Tell the PipeReader how much of the buffer we have consumed
  179. reader.AdvanceTo(buffer.End);
  180. _logger.LogError(ex, "Error processing web socket message");
  181. return;
  182. }
  183. // Tell the PipeReader how much of the buffer we have consumed
  184. reader.AdvanceTo(buffer.End);
  185. _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
  186. var info = new WebSocketMessageInfo
  187. {
  188. MessageType = stub.MessageType,
  189. Data = stub.Data?.ToString(), // Data can be null
  190. Connection = this
  191. };
  192. await OnReceive(info).ConfigureAwait(false);
  193. // Stop reading if there's no more data coming
  194. if (result.IsCompleted)
  195. {
  196. return;
  197. }
  198. }
  199. }
  200. }