WebSocketConnection.cs 7.4 KB

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