WebSocketConnection.cs 8.1 KB

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