WebSocketConnection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. // This info is useful sometimes but also clogs up the log
  159. //_logger.Error("Received web socket message that is not a json structure: " + message);
  160. return;
  161. }
  162. if (OnReceive == null)
  163. {
  164. return;
  165. }
  166. try
  167. {
  168. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  169. var info = new WebSocketMessageInfo
  170. {
  171. MessageType = stub.MessageType,
  172. Data = stub.Data == null ? null : stub.Data.ToString(),
  173. Connection = this
  174. };
  175. OnReceive(info);
  176. }
  177. catch (Exception ex)
  178. {
  179. _logger.ErrorException("Error processing web socket message", ex);
  180. }
  181. }
  182. /// <summary>
  183. /// Sends a message asynchronously.
  184. /// </summary>
  185. /// <typeparam name="T"></typeparam>
  186. /// <param name="message">The message.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>Task.</returns>
  189. /// <exception cref="System.ArgumentNullException">message</exception>
  190. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  191. {
  192. if (message == null)
  193. {
  194. throw new ArgumentNullException("message");
  195. }
  196. var json = _jsonSerializer.SerializeToString(message);
  197. return SendAsync(json, cancellationToken);
  198. }
  199. /// <summary>
  200. /// Sends a message asynchronously.
  201. /// </summary>
  202. /// <param name="buffer">The buffer.</param>
  203. /// <param name="cancellationToken">The cancellation token.</param>
  204. /// <returns>Task.</returns>
  205. public async Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  206. {
  207. if (buffer == null)
  208. {
  209. throw new ArgumentNullException("buffer");
  210. }
  211. cancellationToken.ThrowIfCancellationRequested();
  212. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  213. // This should help us workaround that and ensure all messages get sent
  214. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  215. try
  216. {
  217. await _socket.SendAsync(buffer, true, cancellationToken);
  218. }
  219. catch (OperationCanceledException)
  220. {
  221. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  222. throw;
  223. }
  224. catch (Exception ex)
  225. {
  226. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  227. throw;
  228. }
  229. finally
  230. {
  231. _sendSemaphore.Release();
  232. }
  233. }
  234. public async Task SendAsync(string text, CancellationToken cancellationToken)
  235. {
  236. if (string.IsNullOrWhiteSpace(text))
  237. {
  238. throw new ArgumentNullException("text");
  239. }
  240. cancellationToken.ThrowIfCancellationRequested();
  241. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  242. // This should help us workaround that and ensure all messages get sent
  243. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  244. try
  245. {
  246. await _socket.SendAsync(text, true, cancellationToken);
  247. }
  248. catch (OperationCanceledException)
  249. {
  250. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  251. throw;
  252. }
  253. catch (Exception ex)
  254. {
  255. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  256. throw;
  257. }
  258. finally
  259. {
  260. _sendSemaphore.Release();
  261. }
  262. }
  263. /// <summary>
  264. /// Gets the state.
  265. /// </summary>
  266. /// <value>The state.</value>
  267. public WebSocketState State
  268. {
  269. get { return _socket.State; }
  270. }
  271. /// <summary>
  272. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  273. /// </summary>
  274. public void Dispose()
  275. {
  276. Dispose(true);
  277. GC.SuppressFinalize(this);
  278. }
  279. /// <summary>
  280. /// Releases unmanaged and - optionally - managed resources.
  281. /// </summary>
  282. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  283. protected virtual void Dispose(bool dispose)
  284. {
  285. if (dispose)
  286. {
  287. _cancellationTokenSource.Dispose();
  288. _socket.Dispose();
  289. }
  290. }
  291. }
  292. }