WebSocketConnection.cs 8.9 KB

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