BasePeriodicWebSocketListener.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Model.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace MediaBrowser.Common.Kernel
  9. {
  10. /// <summary>
  11. /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received
  12. /// </summary>
  13. /// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam>
  14. /// <typeparam name="TStateType">The type of the T state type.</typeparam>
  15. public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IDisposable
  16. where TStateType : class, new()
  17. {
  18. /// <summary>
  19. /// The _active connections
  20. /// </summary>
  21. protected readonly List<Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim>> ActiveConnections =
  22. new List<Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim>>();
  23. /// <summary>
  24. /// Gets the name.
  25. /// </summary>
  26. /// <value>The name.</value>
  27. protected abstract string Name { get; }
  28. /// <summary>
  29. /// Gets the data to send.
  30. /// </summary>
  31. /// <param name="state">The state.</param>
  32. /// <returns>Task{`1}.</returns>
  33. protected abstract Task<TReturnDataType> GetDataToSend(TStateType state);
  34. /// <summary>
  35. /// The logger
  36. /// </summary>
  37. protected ILogger Logger;
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="BasePeriodicWebSocketListener{TStateType}" /> class.
  40. /// </summary>
  41. /// <param name="logger">The logger.</param>
  42. /// <exception cref="System.ArgumentNullException">logger</exception>
  43. protected BasePeriodicWebSocketListener(ILogger logger)
  44. {
  45. if (logger == null)
  46. {
  47. throw new ArgumentNullException("logger");
  48. }
  49. Logger = logger;
  50. }
  51. /// <summary>
  52. /// The null task result
  53. /// </summary>
  54. protected Task NullTaskResult = Task.FromResult(true);
  55. /// <summary>
  56. /// Processes the message.
  57. /// </summary>
  58. /// <param name="message">The message.</param>
  59. /// <returns>Task.</returns>
  60. public Task ProcessMessage(WebSocketMessageInfo message)
  61. {
  62. if (message.MessageType.Equals(Name + "Start", StringComparison.OrdinalIgnoreCase))
  63. {
  64. Start(message);
  65. }
  66. if (message.MessageType.Equals(Name + "Stop", StringComparison.OrdinalIgnoreCase))
  67. {
  68. Stop(message);
  69. }
  70. return NullTaskResult;
  71. }
  72. /// <summary>
  73. /// Starts sending messages over a web socket
  74. /// </summary>
  75. /// <param name="message">The message.</param>
  76. private void Start(WebSocketMessageInfo message)
  77. {
  78. var vals = message.Data.Split(',');
  79. var dueTimeMs = long.Parse(vals[0]);
  80. var periodMs = long.Parse(vals[1]);
  81. var cancellationTokenSource = new CancellationTokenSource();
  82. Logger.Info("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name);
  83. var timer = new Timer(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite);
  84. var state = new TStateType();
  85. var semaphore = new SemaphoreSlim(1, 1);
  86. lock (ActiveConnections)
  87. {
  88. ActiveConnections.Add(new Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim>(message.Connection, cancellationTokenSource, timer, state, semaphore));
  89. }
  90. timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs));
  91. }
  92. /// <summary>
  93. /// Timers the callback.
  94. /// </summary>
  95. /// <param name="state">The state.</param>
  96. private async void TimerCallback(object state)
  97. {
  98. var connection = (WebSocketConnection)state;
  99. Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim> tuple;
  100. lock (ActiveConnections)
  101. {
  102. tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection);
  103. }
  104. if (tuple == null)
  105. {
  106. return;
  107. }
  108. if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested)
  109. {
  110. DisposeConnection(tuple);
  111. return;
  112. }
  113. try
  114. {
  115. await tuple.Item5.WaitAsync(tuple.Item2.Token).ConfigureAwait(false);
  116. var data = await GetDataToSend(tuple.Item4).ConfigureAwait(false);
  117. await connection.SendAsync(new WebSocketMessage<TReturnDataType>
  118. {
  119. MessageType = Name,
  120. Data = data
  121. }, tuple.Item2.Token).ConfigureAwait(false);
  122. }
  123. catch (OperationCanceledException)
  124. {
  125. if (tuple.Item2.IsCancellationRequested)
  126. {
  127. DisposeConnection(tuple);
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. Logger.ErrorException("Error sending web socket message {0}", ex, Name);
  133. DisposeConnection(tuple);
  134. }
  135. finally
  136. {
  137. tuple.Item5.Release();
  138. }
  139. }
  140. /// <summary>
  141. /// Stops sending messages over a web socket
  142. /// </summary>
  143. /// <param name="message">The message.</param>
  144. private void Stop(WebSocketMessageInfo message)
  145. {
  146. lock (ActiveConnections)
  147. {
  148. var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection);
  149. if (connection != null)
  150. {
  151. DisposeConnection(connection);
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// Disposes the connection.
  157. /// </summary>
  158. /// <param name="connection">The connection.</param>
  159. private void DisposeConnection(Tuple<WebSocketConnection, CancellationTokenSource, Timer, TStateType, SemaphoreSlim> connection)
  160. {
  161. Logger.Info("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name);
  162. try
  163. {
  164. connection.Item3.Dispose();
  165. }
  166. catch (ObjectDisposedException)
  167. {
  168. }
  169. try
  170. {
  171. connection.Item2.Cancel();
  172. connection.Item2.Dispose();
  173. }
  174. catch (ObjectDisposedException)
  175. {
  176. }
  177. try
  178. {
  179. connection.Item5.Dispose();
  180. }
  181. catch (ObjectDisposedException)
  182. {
  183. }
  184. ActiveConnections.Remove(connection);
  185. }
  186. /// <summary>
  187. /// Releases unmanaged and - optionally - managed resources.
  188. /// </summary>
  189. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  190. protected virtual void Dispose(bool dispose)
  191. {
  192. if (dispose)
  193. {
  194. lock (ActiveConnections)
  195. {
  196. foreach (var connection in ActiveConnections.ToList())
  197. {
  198. DisposeConnection(connection);
  199. }
  200. }
  201. }
  202. }
  203. /// <summary>
  204. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  205. /// </summary>
  206. public void Dispose()
  207. {
  208. Dispose(true);
  209. }
  210. }
  211. }