WebSocketConnection.cs 8.1 KB

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