WebSocketConnection.cs 9.8 KB

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