WebSocketConnection.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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.OnReceiveDelegate = OnReceiveInternal;
  79. RemoteEndPoint = remoteEndPoint;
  80. _logger = logger;
  81. }
  82. /// <summary>
  83. /// Called when [receive].
  84. /// </summary>
  85. /// <param name="bytes">The bytes.</param>
  86. private void OnReceiveInternal(byte[] bytes)
  87. {
  88. LastActivityDate = DateTime.UtcNow;
  89. if (OnReceive == null)
  90. {
  91. return;
  92. }
  93. try
  94. {
  95. WebSocketMessageInfo info;
  96. using (var memoryStream = new MemoryStream(bytes))
  97. {
  98. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromStream(memoryStream, typeof(WebSocketMessage<object>));
  99. info = new WebSocketMessageInfo
  100. {
  101. MessageType = stub.MessageType,
  102. Data = stub.Data == null ? null : stub.Data.ToString()
  103. };
  104. }
  105. info.Connection = this;
  106. OnReceive(info);
  107. }
  108. catch (Exception ex)
  109. {
  110. _logger.ErrorException("Error processing web socket message", ex);
  111. }
  112. }
  113. /// <summary>
  114. /// Sends a message asynchronously.
  115. /// </summary>
  116. /// <typeparam name="T"></typeparam>
  117. /// <param name="message">The message.</param>
  118. /// <param name="cancellationToken">The cancellation token.</param>
  119. /// <returns>Task.</returns>
  120. /// <exception cref="System.ArgumentNullException">message</exception>
  121. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  122. {
  123. if (message == null)
  124. {
  125. throw new ArgumentNullException("message");
  126. }
  127. var bytes = _jsonSerializer.SerializeToBytes(message);
  128. return SendAsync(bytes, cancellationToken);
  129. }
  130. /// <summary>
  131. /// Sends a message asynchronously.
  132. /// </summary>
  133. /// <param name="buffer">The buffer.</param>
  134. /// <param name="cancellationToken">The cancellation token.</param>
  135. /// <returns>Task.</returns>
  136. public Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  137. {
  138. return SendAsync(buffer, WebSocketMessageType.Text, cancellationToken);
  139. }
  140. /// <summary>
  141. /// Sends a message asynchronously.
  142. /// </summary>
  143. /// <param name="buffer">The buffer.</param>
  144. /// <param name="type">The type.</param>
  145. /// <param name="cancellationToken">The cancellation token.</param>
  146. /// <returns>Task.</returns>
  147. /// <exception cref="System.ArgumentNullException">buffer</exception>
  148. public async Task SendAsync(byte[] buffer, WebSocketMessageType type, CancellationToken cancellationToken)
  149. {
  150. if (buffer == null)
  151. {
  152. throw new ArgumentNullException("buffer");
  153. }
  154. if (cancellationToken == null)
  155. {
  156. throw new ArgumentNullException("cancellationToken");
  157. }
  158. cancellationToken.ThrowIfCancellationRequested();
  159. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  160. // This should help us workaround that and ensure all messages get sent
  161. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  162. try
  163. {
  164. await _socket.SendAsync(buffer, type, true, cancellationToken);
  165. }
  166. catch (OperationCanceledException)
  167. {
  168. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  169. throw;
  170. }
  171. catch (Exception ex)
  172. {
  173. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  174. throw;
  175. }
  176. finally
  177. {
  178. _sendSemaphore.Release();
  179. }
  180. }
  181. /// <summary>
  182. /// Gets the state.
  183. /// </summary>
  184. /// <value>The state.</value>
  185. public WebSocketState State
  186. {
  187. get { return _socket.State; }
  188. }
  189. /// <summary>
  190. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  191. /// </summary>
  192. public void Dispose()
  193. {
  194. Dispose(true);
  195. GC.SuppressFinalize(this);
  196. }
  197. /// <summary>
  198. /// Releases unmanaged and - optionally - managed resources.
  199. /// </summary>
  200. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  201. protected virtual void Dispose(bool dispose)
  202. {
  203. if (dispose)
  204. {
  205. _cancellationTokenSource.Dispose();
  206. _socket.Dispose();
  207. }
  208. }
  209. }
  210. }