BasePeriodicWebSocketListener.cs 7.3 KB

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