WebSocketConnection.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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<WebSocketConnection> _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. /// <inheritdoc />
  71. public DateTime LastKeepAliveDate { get; set; }
  72. /// <summary>
  73. /// Gets or sets the query string.
  74. /// </summary>
  75. /// <value>The query string.</value>
  76. public IQueryCollection QueryString { get; }
  77. /// <summary>
  78. /// Gets the state.
  79. /// </summary>
  80. /// <value>The state.</value>
  81. public WebSocketState State => _socket.State;
  82. /// <summary>
  83. /// Sends a message asynchronously.
  84. /// </summary>
  85. /// <typeparam name="T"></typeparam>
  86. /// <param name="message">The message.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. /// <returns>Task.</returns>
  89. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  90. {
  91. var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
  92. return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
  93. }
  94. /// <inheritdoc />
  95. public async Task ProcessAsync(CancellationToken cancellationToken = default)
  96. {
  97. var pipe = new Pipe();
  98. var writer = pipe.Writer;
  99. ValueWebSocketReceiveResult receiveresult;
  100. do
  101. {
  102. // Allocate at least 512 bytes from the PipeWriter
  103. Memory<byte> memory = writer.GetMemory(512);
  104. try
  105. {
  106. receiveresult = await _socket.ReceiveAsync(memory, cancellationToken);
  107. }
  108. catch (WebSocketException ex)
  109. {
  110. _logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
  111. break;
  112. }
  113. int bytesRead = receiveresult.Count;
  114. if (bytesRead == 0)
  115. {
  116. break;
  117. }
  118. // Tell the PipeWriter how much was read from the Socket
  119. writer.Advance(bytesRead);
  120. // Make the data available to the PipeReader
  121. FlushResult flushResult = await writer.FlushAsync();
  122. if (flushResult.IsCompleted)
  123. {
  124. // The PipeReader stopped reading
  125. break;
  126. }
  127. LastActivityDate = DateTime.UtcNow;
  128. if (receiveresult.EndOfMessage)
  129. {
  130. await ProcessInternal(pipe.Reader).ConfigureAwait(false);
  131. }
  132. } while (
  133. (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
  134. && receiveresult.MessageType != WebSocketMessageType.Close);
  135. Closed?.Invoke(this, EventArgs.Empty);
  136. if (_socket.State == WebSocketState.Open
  137. || _socket.State == WebSocketState.CloseReceived
  138. || _socket.State == WebSocketState.CloseSent)
  139. {
  140. await _socket.CloseAsync(
  141. WebSocketCloseStatus.NormalClosure,
  142. string.Empty,
  143. cancellationToken).ConfigureAwait(false);
  144. }
  145. }
  146. private async Task ProcessInternal(PipeReader reader)
  147. {
  148. ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
  149. ReadOnlySequence<byte> buffer = result.Buffer;
  150. if (OnReceive == null)
  151. {
  152. // Tell the PipeReader how much of the buffer we have consumed
  153. reader.AdvanceTo(buffer.End);
  154. return;
  155. }
  156. WebSocketMessage<object> stub;
  157. try
  158. {
  159. if (buffer.IsSingleSegment)
  160. {
  161. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buffer.FirstSpan, _jsonOptions);
  162. }
  163. else
  164. {
  165. var buf = ArrayPool<byte>.Shared.Rent(Convert.ToInt32(buffer.Length));
  166. try
  167. {
  168. buffer.CopyTo(buf);
  169. stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buf, _jsonOptions);
  170. }
  171. finally
  172. {
  173. ArrayPool<byte>.Shared.Return(buf);
  174. }
  175. }
  176. }
  177. catch (JsonException ex)
  178. {
  179. // Tell the PipeReader how much of the buffer we have consumed
  180. reader.AdvanceTo(buffer.End);
  181. _logger.LogError(ex, "Error processing web socket message");
  182. return;
  183. }
  184. // Tell the PipeReader how much of the buffer we have consumed
  185. reader.AdvanceTo(buffer.End);
  186. _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
  187. var info = new WebSocketMessageInfo
  188. {
  189. MessageType = stub.MessageType,
  190. Data = stub.Data?.ToString(), // Data can be null
  191. Connection = this
  192. };
  193. if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal))
  194. {
  195. await SendKeepAliveResponse();
  196. }
  197. else
  198. {
  199. await OnReceive(info).ConfigureAwait(false);
  200. }
  201. }
  202. private Task SendKeepAliveResponse()
  203. {
  204. LastKeepAliveDate = DateTime.UtcNow;
  205. return SendAsync(new WebSocketMessage<string>
  206. {
  207. MessageType = "KeepAlive"
  208. }, CancellationToken.None);
  209. }
  210. /// <inheritdoc />
  211. public void Dispose()
  212. {
  213. Dispose(true);
  214. GC.SuppressFinalize(this);
  215. }
  216. /// <summary>
  217. /// Releases unmanaged and - optionally - managed resources.
  218. /// </summary>
  219. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  220. protected virtual void Dispose(bool dispose)
  221. {
  222. if (dispose)
  223. {
  224. _socket.Dispose();
  225. }
  226. }
  227. }
  228. }