WebSocketConnection.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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.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. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  60. /// </summary>
  61. /// <param name="socket">The socket.</param>
  62. /// <param name="remoteEndPoint">The remote end point.</param>
  63. /// <param name="jsonSerializer">The json serializer.</param>
  64. /// <param name="logger">The logger.</param>
  65. /// <exception cref="System.ArgumentNullException">socket</exception>
  66. public WebSocketConnection(IWebSocket socket, string remoteEndPoint, IJsonSerializer jsonSerializer, ILogger logger)
  67. {
  68. if (socket == null)
  69. {
  70. throw new ArgumentNullException("socket");
  71. }
  72. if (string.IsNullOrEmpty(remoteEndPoint))
  73. {
  74. throw new ArgumentNullException("remoteEndPoint");
  75. }
  76. if (jsonSerializer == null)
  77. {
  78. throw new ArgumentNullException("jsonSerializer");
  79. }
  80. if (logger == null)
  81. {
  82. throw new ArgumentNullException("logger");
  83. }
  84. Id = Guid.NewGuid();
  85. _jsonSerializer = jsonSerializer;
  86. _socket = socket;
  87. _socket.OnReceiveBytes = OnReceiveInternal;
  88. _socket.OnReceive = OnReceiveInternal;
  89. RemoteEndPoint = remoteEndPoint;
  90. _logger = logger;
  91. socket.Closed += socket_Closed;
  92. }
  93. void socket_Closed(object sender, EventArgs e)
  94. {
  95. EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
  96. }
  97. /// <summary>
  98. /// Called when [receive].
  99. /// </summary>
  100. /// <param name="bytes">The bytes.</param>
  101. private void OnReceiveInternal(byte[] bytes)
  102. {
  103. LastActivityDate = DateTime.UtcNow;
  104. if (OnReceive == null)
  105. {
  106. return;
  107. }
  108. try
  109. {
  110. //_logger.Debug(Encoding.UTF8.GetString(bytes));
  111. using (var memoryStream = new MemoryStream(bytes))
  112. {
  113. var info = (WebSocketMessageInfo)_jsonSerializer.DeserializeFromStream(memoryStream, typeof(WebSocketMessageInfo));
  114. //info = new WebSocketMessageInfo
  115. //{
  116. // MessageType = stub.MessageType,
  117. // Data = stub.Data == null ? null : stub.Data.ToString()
  118. //};
  119. info.Connection = this;
  120. OnReceive(info);
  121. }
  122. }
  123. catch (Exception ex)
  124. {
  125. _logger.ErrorException("Error processing web socket message", ex);
  126. }
  127. }
  128. private void OnReceiveInternal(string message)
  129. {
  130. LastActivityDate = DateTime.UtcNow;
  131. if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
  132. {
  133. _logger.Error("Received web socket message that is not a json structure: " + message);
  134. return;
  135. }
  136. if (OnReceive == null)
  137. {
  138. return;
  139. }
  140. try
  141. {
  142. var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromString(message, typeof(WebSocketMessage<object>));
  143. var info = new WebSocketMessageInfo
  144. {
  145. MessageType = stub.MessageType,
  146. Data = stub.Data == null ? null : stub.Data.ToString(),
  147. Connection = this
  148. };
  149. OnReceive(info);
  150. }
  151. catch (Exception ex)
  152. {
  153. _logger.ErrorException("Error processing web socket message", ex);
  154. }
  155. }
  156. /// <summary>
  157. /// Sends a message asynchronously.
  158. /// </summary>
  159. /// <typeparam name="T"></typeparam>
  160. /// <param name="message">The message.</param>
  161. /// <param name="cancellationToken">The cancellation token.</param>
  162. /// <returns>Task.</returns>
  163. /// <exception cref="System.ArgumentNullException">message</exception>
  164. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  165. {
  166. if (message == null)
  167. {
  168. throw new ArgumentNullException("message");
  169. }
  170. var json = _jsonSerializer.SerializeToString(message);
  171. return SendAsync(json, cancellationToken);
  172. }
  173. /// <summary>
  174. /// Sends a message asynchronously.
  175. /// </summary>
  176. /// <param name="buffer">The buffer.</param>
  177. /// <param name="cancellationToken">The cancellation token.</param>
  178. /// <returns>Task.</returns>
  179. public async Task SendAsync(byte[] buffer, CancellationToken cancellationToken)
  180. {
  181. if (buffer == null)
  182. {
  183. throw new ArgumentNullException("buffer");
  184. }
  185. cancellationToken.ThrowIfCancellationRequested();
  186. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  187. // This should help us workaround that and ensure all messages get sent
  188. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  189. try
  190. {
  191. await _socket.SendAsync(buffer, true, cancellationToken);
  192. }
  193. catch (OperationCanceledException)
  194. {
  195. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  196. throw;
  197. }
  198. catch (Exception ex)
  199. {
  200. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  201. throw;
  202. }
  203. finally
  204. {
  205. _sendSemaphore.Release();
  206. }
  207. }
  208. public async Task SendAsync(string text, CancellationToken cancellationToken)
  209. {
  210. if (string.IsNullOrWhiteSpace(text))
  211. {
  212. throw new ArgumentNullException("text");
  213. }
  214. cancellationToken.ThrowIfCancellationRequested();
  215. // Per msdn docs, attempting to send simultaneous messages will result in one failing.
  216. // This should help us workaround that and ensure all messages get sent
  217. await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  218. try
  219. {
  220. await _socket.SendAsync(text, true, cancellationToken);
  221. }
  222. catch (OperationCanceledException)
  223. {
  224. _logger.Info("WebSocket message to {0} was cancelled", RemoteEndPoint);
  225. throw;
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.ErrorException("Error sending WebSocket message {0}", ex, RemoteEndPoint);
  230. throw;
  231. }
  232. finally
  233. {
  234. _sendSemaphore.Release();
  235. }
  236. }
  237. /// <summary>
  238. /// Gets the state.
  239. /// </summary>
  240. /// <value>The state.</value>
  241. public WebSocketState State
  242. {
  243. get { return _socket.State; }
  244. }
  245. /// <summary>
  246. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  247. /// </summary>
  248. public void Dispose()
  249. {
  250. Dispose(true);
  251. GC.SuppressFinalize(this);
  252. }
  253. /// <summary>
  254. /// Releases unmanaged and - optionally - managed resources.
  255. /// </summary>
  256. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  257. protected virtual void Dispose(bool dispose)
  258. {
  259. if (dispose)
  260. {
  261. _cancellationTokenSource.Dispose();
  262. _socket.Dispose();
  263. }
  264. }
  265. }
  266. }