WebSocketConnection.cs 7.4 KB

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