WebSocketConnection.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Controller.Net;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Model.Net;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Specialized;
  8. using System.IO;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Server.Implementations.ServerManager
  12. {
  13. /// <summary>
  14. /// Class WebSocketConnection
  15. /// </summary>
  16. public class WebSocketConnection : IWebSocketConnection
  17. {
  18. public event EventHandler<EventArgs> Closed;
  19. /// <summary>
  20. /// The _socket
  21. /// </summary>
  22. private readonly IWebSocket _socket;
  23. /// <summary>
  24. /// The _remote end point
  25. /// </summary>
  26. public string RemoteEndPoint { get; private set; }
  27. /// <summary>
  28. /// The _cancellation token source
  29. /// </summary>
  30. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  31. /// <summary>
  32. /// The _send semaphore
  33. /// </summary>
  34. private readonly SemaphoreSlim _sendSemaphore = new SemaphoreSlim(1, 1);
  35. /// <summary>
  36. /// The logger
  37. /// </summary>
  38. private readonly ILogger _logger;
  39. /// <summary>
  40. /// The _json serializer
  41. /// </summary>
  42. private readonly IJsonSerializer _jsonSerializer;
  43. /// <summary>
  44. /// Gets or sets the receive action.
  45. /// </summary>
  46. /// <value>The receive action.</value>
  47. public Action<WebSocketMessageInfo> OnReceive { get; set; }
  48. /// <summary>
  49. /// Gets the last activity date.
  50. /// </summary>
  51. /// <value>The last activity date.</value>
  52. public DateTime LastActivityDate { get; private set; }
  53. /// <summary>
  54. /// Gets the id.
  55. /// </summary>
  56. /// <value>The id.</value>
  57. public Guid Id { get; private set; }
  58. /// <summary>
  59. /// Gets or sets the URL.
  60. /// </summary>
  61. /// <value>The URL.</value>
  62. public string Url { get; set; }
  63. /// <summary>
  64. /// Gets or sets the query string.
  65. /// </summary>
  66. /// <value>The query string.</value>
  67. public NameValueCollection QueryString { get; set; }
  68. /// <summary>
  69. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  70. /// </summary>
  71. /// <param name="socket">The socket.</param>
  72. /// <param name="remoteEndPoint">The remote end point.</param>
  73. /// <param name="jsonSerializer">The json serializer.</param>
  74. /// <param name="logger">The logger.</param>
  75. /// <exception cref="System.ArgumentNullException">socket</exception>
  76. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
  77. {
  78. if (socket == null)
  79. {
  80. throw new ArgumentNullException("socket");
  81. }
  82. if (string.IsNullOrEmpty(remoteEndPoint))
  83. {
  84. throw new ArgumentNullException("remoteEndPoint");
  85. }
  86. if (jsonSerializer == null)
  87. {
  88. throw new ArgumentNullException("jsonSerializer");
  89. }
  90. if (logger == null)
  91. {
  92. throw new ArgumentNullException("logger");
  93. }
  94. Id = Guid.NewGuid();
  95. _jsonSerializer = jsonSerializer;
  96. _socket = socket;
  97. _socket.OnReceiveBytes = OnReceiveInternal;
  98. _socket.OnReceive = OnReceiveInternal;
  99. RemoteEndPoint = remoteEndPoint;
  100. _logger = logger;
  101. socket.Closed += socket_Closed;
  102. }
  103. void socket_Closed(object sender, EventArgs e)
  104. {
  105. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  106. }
  107. /// <summary>
  108. /// Called when [receive].
  109. /// </summary>
  110. /// <param name="bytes">The bytes.</param>
  111. private void OnReceiveInternal(byte[] bytes)
  112. {
  113. LastActivityDate = DateTime.UtcNow;
  114. if (OnReceive == null)
  115. {
  116. return;
  117. }
  118. try
  119. {
  120. //_logger.Debug(Encoding.UTF8.GetString(bytes));
  121. using (var memoryStream = new MemoryStream(bytes))
  122. {
  123. var info = (WebSocketMessageInfo)_jsonSerializer.DeserializeFromStream(memoryStream, typeof(WebSocketMessageInfo));
  124. //info = new WebSocketMessageInfo
  125. //{
  126. // MessageType = stub.MessageType,
  127. // Data = stub.Data == null ? null : stub.Data.ToString()
  128. //};
  129. info.Connection = this;
  130. OnReceive(info);
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. _logger.ErrorException("Error processing web socket message", ex);
  136. }
  137. }
  138. private void OnReceiveInternal(string message)
  139. {
  140. LastActivityDate = DateTime.UtcNow;
  141. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  142. {
  143. _logger.Error("Received web socket message that is not a json structure: " + message);
  144. return;
  145. }
  146. if (OnReceive == null)
  147. {
  148. return;
  149. }
  150. try
  151. {
  152. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  153. var info = new WebSocketMessageInfo
  154. {
  155. MessageType = stub.MessageType,
  156. Data = stub.Data == null ? null : stub.Data.ToString(),
  157. Connection = this
  158. };
  159. OnReceive(info);
  160. }
  161. catch (Exception ex)
  162. {
  163. _logger.ErrorException("Error processing web socket message", ex);
  164. }
  165. }
  166. /// <summary>
  167. /// Sends a message asynchronously.
  168. /// </summary>
  169. /// <typeparam name="T"></typeparam>
  170. /// <param name="message">The message.</param>
  171. /// <param name="cancellationToken">The cancellation token.</param>
  172. /// <returns>Task.</returns>
  173. /// <exception cref="System.ArgumentNullException">message</exception>
  174. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  175. {
  176. if (message == null)
  177. {
  178. throw new ArgumentNullException("message");
  179. }
  180. var json = _jsonSerializer.SerializeToString(message);
  181. return SendAsync(json, cancellationToken);
  182. }
  183. /// <summary>
  184. /// Sends a message asynchronously.
  185. /// </summary>
  186. /// <param name="buffer">The buffer.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>Task.</returns>
  189. public async Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  190. {
  191. if (buffer == null)
  192. {
  193. throw new ArgumentNullException("buffer");
  194. }
  195. cancellationToken.ThrowIfCancellationRequested();
  196. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  197. // This should help us workaround that and ensure all messages get sent
  198. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  199. try
  200. {
  201. await _socket.SendAsync(buffer, true, cancellationToken);
  202. }
  203. catch (OperationCanceledException)
  204. {
  205. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  206. throw;
  207. }
  208. catch (Exception ex)
  209. {
  210. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  211. throw;
  212. }
  213. finally
  214. {
  215. _sendSemaphore.Release();
  216. }
  217. }
  218. public async Task SendAsync(string text, CancellationToken cancellationToken)
  219. {
  220. if (string.IsNullOrWhiteSpace(text))
  221. {
  222. throw new ArgumentNullException("text");
  223. }
  224. cancellationToken.ThrowIfCancellationRequested();
  225. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  226. // This should help us workaround that and ensure all messages get sent
  227. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  228. try
  229. {
  230. await _socket.SendAsync(text, true, cancellationToken);
  231. }
  232. catch (OperationCanceledException)
  233. {
  234. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  235. throw;
  236. }
  237. catch (Exception ex)
  238. {
  239. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  240. throw;
  241. }
  242. finally
  243. {
  244. _sendSemaphore.Release();
  245. }
  246. }
  247. /// <summary>
  248. /// Gets the state.
  249. /// </summary>
  250. /// <value>The state.</value>
  251. public WebSocketState State
  252. {
  253. get { return _socket.State; }
  254. }
  255. /// <summary>
  256. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  257. /// </summary>
  258. public void Dispose()
  259. {
  260. Dispose(true);
  261. GC.SuppressFinalize(this);
  262. }
  263. /// <summary>
  264. /// Releases unmanaged and - optionally - managed resources.
  265. /// </summary>
  266. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  267. protected virtual void Dispose(bool dispose)
  268. {
  269. if (dispose)
  270. {
  271. _cancellationTokenSource.Dispose();
  272. _socket.Dispose();
  273. }
  274. }
  275. }
  276. }