WebSocketConnection.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System.Text;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Controller.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Specialized;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Services;
  14. using MediaBrowser.Model.Text;
  15. namespace Emby.Server.Implementations.ServerManager
  16. {
  17. /// <summary>
  18. /// Class WebSocketConnection
  19. /// </summary>
  20. public class WebSocketConnection : IWebSocketConnection
  21. {
  22. public event EventHandler<EventArgs> Closed;
  23. /// <summary>
  24. /// The _socket
  25. /// </summary>
  26. private readonly IWebSocket _socket;
  27. /// <summary>
  28. /// The _remote end point
  29. /// </summary>
  30. public string RemoteEndPoint { get; private set; }
  31. /// <summary>
  32. /// The _cancellation token source
  33. /// </summary>
  34. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  35. /// <summary>
  36. /// The logger
  37. /// </summary>
  38. private readonly ILogger _logger;
  39. /// <summary>
  40. /// The _json serializer
  41. /// </summary>
  42. private readonly IJsonSerializer _jsonSerializer;
  43. /// <summary>
  44. /// Gets or sets the receive action.
  45. /// </summary>
  46. /// <value>The receive action.</value>
  47. public Action<WebSocketMessageInfo> OnReceive { get; set; }
  48. /// <summary>
  49. /// Gets the last activity date.
  50. /// </summary>
  51. /// <value>The last activity date.</value>
  52. public DateTime LastActivityDate { get; private set; }
  53. /// <summary>
  54. /// Gets the id.
  55. /// </summary>
  56. /// <value>The id.</value>
  57. public Guid Id { get; private set; }
  58. /// <summary>
  59. /// Gets or sets the URL.
  60. /// </summary>
  61. /// <value>The URL.</value>
  62. public string Url { get; set; }
  63. /// <summary>
  64. /// Gets or sets the query string.
  65. /// </summary>
  66. /// <value>The query string.</value>
  67. public QueryParamCollection QueryString { get; set; }
  68. private readonly IMemoryStreamFactory _memoryStreamProvider;
  69. private readonly ITextEncoding _textEncoding;
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  72. /// </summary>
  73. /// <param name="socket">The socket.</param>
  74. /// <param name="remoteEndPoint">The remote end point.</param>
  75. /// <param name="jsonSerializer">The json serializer.</param>
  76. /// <param name="logger">The logger.</param>
  77. /// <exception cref="System.ArgumentNullException">socket</exception>
  78. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding)
  79. {
  80. if (socket == null)
  81. {
  82. throw new ArgumentNullException("socket");
  83. }
  84. if (string.IsNullOrEmpty(remoteEndPoint))
  85. {
  86. throw new ArgumentNullException("remoteEndPoint");
  87. }
  88. if (jsonSerializer == null)
  89. {
  90. throw new ArgumentNullException("jsonSerializer");
  91. }
  92. if (logger == null)
  93. {
  94. throw new ArgumentNullException("logger");
  95. }
  96. Id = Guid.NewGuid();
  97. _jsonSerializer = jsonSerializer;
  98. _socket = socket;
  99. _socket.OnReceiveBytes = OnReceiveInternal;
  100. _socket.OnReceive = OnReceiveInternal;
  101. RemoteEndPoint = remoteEndPoint;
  102. _logger = logger;
  103. _memoryStreamProvider = memoryStreamProvider;
  104. _textEncoding = textEncoding;
  105. socket.Closed += socket_Closed;
  106. }
  107. void socket_Closed(object sender, EventArgs e)
  108. {
  109. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  110. }
  111. /// <summary>
  112. /// Called when [receive].
  113. /// </summary>
  114. /// <param name="bytes">The bytes.</param>
  115. private void OnReceiveInternal(byte[] bytes)
  116. {
  117. LastActivityDate = DateTime.UtcNow;
  118. if (OnReceive == null)
  119. {
  120. return;
  121. }
  122. var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, null, false);
  123. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  124. {
  125. OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  126. }
  127. else
  128. {
  129. OnReceiveInternal(_textEncoding.GetASCIIEncoding().GetString(bytes, 0, bytes.Length));
  130. }
  131. }
  132. private void OnReceiveInternal(string message)
  133. {
  134. LastActivityDate = DateTime.UtcNow;
  135. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  136. {
  137. // This info is useful sometimes but also clogs up the log
  138. //_logger.Error("Received web socket message that is not a json structure: " + message);
  139. return;
  140. }
  141. if (OnReceive == null)
  142. {
  143. return;
  144. }
  145. try
  146. {
  147. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  148. var info = new WebSocketMessageInfo
  149. {
  150. MessageType = stub.MessageType,
  151. Data = stub.Data == null ? null : stub.Data.ToString(),
  152. Connection = this
  153. };
  154. OnReceive(info);
  155. }
  156. catch (Exception ex)
  157. {
  158. _logger.ErrorException("Error processing web socket message", ex);
  159. }
  160. }
  161. /// <summary>
  162. /// Sends a message asynchronously.
  163. /// </summary>
  164. /// <typeparam name="T"></typeparam>
  165. /// <param name="message">The message.</param>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <returns>Task.</returns>
  168. /// <exception cref="System.ArgumentNullException">message</exception>
  169. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  170. {
  171. if (message == null)
  172. {
  173. throw new ArgumentNullException("message");
  174. }
  175. var json = _jsonSerializer.SerializeToString(message);
  176. return SendAsync(json, cancellationToken);
  177. }
  178. /// <summary>
  179. /// Sends a message asynchronously.
  180. /// </summary>
  181. /// <param name="buffer">The buffer.</param>
  182. /// <param name="cancellationToken">The cancellation token.</param>
  183. /// <returns>Task.</returns>
  184. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  185. {
  186. if (buffer == null)
  187. {
  188. throw new ArgumentNullException("buffer");
  189. }
  190. cancellationToken.ThrowIfCancellationRequested();
  191. return _socket.SendAsync(buffer, true, cancellationToken);
  192. }
  193. public Task SendAsync(string text, CancellationToken cancellationToken)
  194. {
  195. if (string.IsNullOrWhiteSpace(text))
  196. {
  197. throw new ArgumentNullException("text");
  198. }
  199. cancellationToken.ThrowIfCancellationRequested();
  200. return _socket.SendAsync(text, true, cancellationToken);
  201. }
  202. /// <summary>
  203. /// Gets the state.
  204. /// </summary>
  205. /// <value>The state.</value>
  206. public WebSocketState State
  207. {
  208. get { return _socket.State; }
  209. }
  210. /// <summary>
  211. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  212. /// </summary>
  213. public void Dispose()
  214. {
  215. Dispose(true);
  216. GC.SuppressFinalize(this);
  217. }
  218. /// <summary>
  219. /// Releases unmanaged and - optionally - managed resources.
  220. /// </summary>
  221. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  222. protected virtual void Dispose(bool dispose)
  223. {
  224. if (dispose)
  225. {
  226. _cancellationTokenSource.Dispose();
  227. _socket.Dispose();
  228. }
  229. }
  230. }
  231. }