WebSocketConnection.cs 11 KB

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