WebSocketConnection.cs 7.6 KB

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