WebSocketConnection.cs 7.4 KB

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