2
0

WebSocketConnection.cs 7.3 KB

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