WebSocketConnection.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 (OnReceive == null)
  118. {
  119. return;
  120. }
  121. try
  122. {
  123. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  124. var info = new WebSocketMessageInfo
  125. {
  126. MessageType = stub.MessageType,
  127. Data = stub.Data == null ? null : stub.Data.ToString()
  128. };
  129. info.Connection = this;
  130. OnReceive(info);
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.ErrorException("Error processing web socket message", ex);
  135. }
  136. }
  137. /// <summary>
  138. /// Sends a message asynchronously.
  139. /// </summary>
  140. /// <typeparam name="T"></typeparam>
  141. /// <param name="message">The message.</param>
  142. /// <param name="cancellationToken">The cancellation token.</param>
  143. /// <returns>Task.</returns>
  144. /// <exception cref="System.ArgumentNullException">message</exception>
  145. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  146. {
  147. if (message == null)
  148. {
  149. throw new ArgumentNullException("message");
  150. }
  151. var bytes = _jsonSerializer.SerializeToBytes(message);
  152. return SendAsync(bytes, cancellationToken);
  153. }
  154. /// <summary>
  155. /// Sends a message asynchronously.
  156. /// </summary>
  157. /// <param name="buffer">The buffer.</param>
  158. /// <param name="cancellationToken">The cancellation token.</param>
  159. /// <returns>Task.</returns>
  160. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  161. {
  162. return SendAsync(buffer, WebSocketMessageType.Text, cancellationToken);
  163. }
  164. /// <summary>
  165. /// Sends a message asynchronously.
  166. /// </summary>
  167. /// <param name="buffer">The buffer.</param>
  168. /// <param name="type">The type.</param>
  169. /// <param name="cancellationToken">The cancellation token.</param>
  170. /// <returns>Task.</returns>
  171. /// <exception cref="System.ArgumentNullException">buffer</exception>
  172. public async Task SendAsync(byte[] buffer, WebSocketMessageType type, CancellationToken cancellationToken)
  173. {
  174. if (buffer == null)
  175. {
  176. throw new ArgumentNullException("buffer");
  177. }
  178. if (cancellationToken == null)
  179. {
  180. throw new ArgumentNullException("cancellationToken");
  181. }
  182. cancellationToken.ThrowIfCancellationRequested();
  183. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  184. // This should help us workaround that and ensure all messages get sent
  185. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  186. try
  187. {
  188. await _socket.SendAsync(buffer, type, true, cancellationToken);
  189. }
  190. catch (OperationCanceledException)
  191. {
  192. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  193. throw;
  194. }
  195. catch (Exception ex)
  196. {
  197. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  198. throw;
  199. }
  200. finally
  201. {
  202. _sendSemaphore.Release();
  203. }
  204. }
  205. /// <summary>
  206. /// Gets the state.
  207. /// </summary>
  208. /// <value>The state.</value>
  209. public WebSocketState State
  210. {
  211. get { return _socket.State; }
  212. }
  213. /// <summary>
  214. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  215. /// </summary>
  216. public void Dispose()
  217. {
  218. Dispose(true);
  219. GC.SuppressFinalize(this);
  220. }
  221. /// <summary>
  222. /// Releases unmanaged and - optionally - managed resources.
  223. /// </summary>
  224. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  225. protected virtual void Dispose(bool dispose)
  226. {
  227. if (dispose)
  228. {
  229. _cancellationTokenSource.Dispose();
  230. _socket.Dispose();
  231. }
  232. }
  233. }
  234. }