WebSocketConnection.cs 9.0 KB

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