ChatConnectionKeeper.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Vinno.IUS.Common.Log;
  5. using Vinno.IUS.Common.Network.Leaf;
  6. using Vinno.IUS.Common.Network.Tcp;
  7. using Vinno.IUS.Common.Network.Transfer;
  8. using Vinno.vCloud.Protocol.Messages.Client;
  9. using Vinno.vCloud.Protocol.Messages.Live;
  10. namespace Vinno.vCloud.Common.FIS.Chat
  11. {
  12. class ChatConnectionKeeper
  13. {
  14. private ClientLeaf _clientLeaf;
  15. private string _roomId;
  16. private string _accountId;
  17. private bool _stopped;
  18. private int _heartBeatInterval = 2;
  19. private bool _heartBeatAlive;
  20. private double _chechInterminal = 3;
  21. private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
  22. /// <summary>
  23. /// The envent connection off line when a wrong eche result happened
  24. /// </summary>
  25. public event EventHandler Offlined;
  26. /// <summary>
  27. /// Raised when the client leaf closed or not online.
  28. /// </summary>
  29. public event EventHandler ClientLeafClosed;
  30. /// <summary>
  31. /// Gets the value to indicate the heart beat is alive or not.
  32. /// </summary>
  33. public bool HeartBeatAlive => _heartBeatAlive;
  34. public ChatConnectionKeeper(string roomId, string accountId, string liveServiceUrl)
  35. {
  36. if (string.IsNullOrEmpty(liveServiceUrl))
  37. {
  38. throw new ArgumentNullException("Url");
  39. }
  40. var args = liveServiceUrl.Split(':');
  41. var host = args[0];
  42. var port = Convert.ToInt32(args[1]);
  43. var tcpCreator = new TcpCreator(host, port);
  44. var rtyCount = 0;
  45. Logger.WriteLineInfo("Start To Create Client Leaf for ChatConnectionKeeper");
  46. _clientLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, tcpCreator);
  47. Logger.WriteLineInfo("Create Client Leaf End for ChatConnectionKeeper");
  48. while (!_clientLeaf.Online && rtyCount < 1)
  49. {
  50. _clientLeaf.Close();
  51. Logger.WriteLineError($"Chat connectionKeeper create leaf offline! url:{liveServiceUrl}, Retry Count {rtyCount}");
  52. rtyCount++;
  53. Thread.Sleep(10);
  54. Logger.WriteLineInfo("Start To Create Client Leaf for ChatConnectionKeeper");
  55. _clientLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, tcpCreator);
  56. Logger.WriteLineInfo("Create Client Leaf End for ChatConnectionKeeper");
  57. }
  58. if (!_clientLeaf.Online)
  59. {
  60. Logger.WriteLineError($"Chat connectionKeeper create leaf offline! url:{liveServiceUrl}, Retry Count {rtyCount}");
  61. }
  62. else
  63. {
  64. Logger.WriteLineInfo($"Chat connectionKeeper create leaf online! url:{liveServiceUrl}, Retry Count {rtyCount}");
  65. }
  66. _roomId = roomId;
  67. _accountId = accountId;
  68. }
  69. /// <summary>
  70. /// Start the Heartrate to keep the session available.
  71. /// </summary>
  72. public async void Start(bool isDelay = true)
  73. {
  74. _stopped = false;
  75. Logger.WriteLineInfo($"Chat connection keeper is started for room: {_roomId}, isDelay{isDelay}");
  76. if (isDelay)
  77. {
  78. await Task.Delay(5000);
  79. }
  80. DoCheck();
  81. }
  82. /// <summary>
  83. /// Stop the Heartrate
  84. /// </summary>
  85. public void Stop()
  86. {
  87. _stopped = true;
  88. _waitEvent.Set();
  89. Logger.WriteLineInfo($"Chat connection keeper is stopped for room: {_roomId}");
  90. if (_clientLeaf != null)
  91. {
  92. _clientLeaf.Close();
  93. _clientLeaf = null;
  94. }
  95. }
  96. private void DoCheck()
  97. {
  98. Task.Run(new Action(ExecuteDoCheck));
  99. }
  100. private void ExecuteDoCheck()
  101. {
  102. try
  103. {
  104. using (var message = new LiveHeartRateRequest())
  105. {
  106. message.RoomId = _roomId;
  107. message.SubscriberId = _accountId;
  108. var result = _clientLeaf.Send(message);
  109. var shouldStop = false;
  110. if (result == null)
  111. {
  112. Logger.WriteLineError($"ChatConnectionKeeper Offlined occurred since result null");
  113. shouldStop = true;
  114. }
  115. else
  116. {
  117. var messageResult = ResultMessage.Convert(result);
  118. if (messageResult == CCR.OK)
  119. {
  120. _heartBeatInterval = 2;
  121. _heartBeatAlive = true;
  122. }
  123. else
  124. {
  125. Logger.WriteLineInfo($"ChatConnectionKeeper Offline occurred sinc none ok result.roomid: {_roomId}, subscriberid:{_accountId}, " +
  126. $"message result: {result?.ToString()}, {result?.GetType()}");
  127. shouldStop = true;
  128. }
  129. }
  130. if (shouldStop)
  131. {
  132. if (_clientLeaf.Online)
  133. {
  134. _clientLeaf.Close();
  135. }
  136. if (!_stopped)
  137. {
  138. Logger.WriteLineInfo($"ChatConnectionKeeper Offlined called since shouldStop");
  139. //Do offline when server has no current chat room
  140. OnOfflined();
  141. }
  142. }
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. Logger.WriteLineError($"ChatConnection keeper ExecuteDoCheck error:{ex}");
  148. _heartBeatAlive = false;
  149. if (!_stopped && _clientLeaf != null)
  150. {
  151. if (_clientLeaf.IsClosed || !_clientLeaf.Online)
  152. {
  153. if (_heartBeatInterval == 2)
  154. {
  155. ClientLeafClosed.Invoke(this, null);
  156. return;
  157. }
  158. }
  159. else
  160. {
  161. if (_heartBeatInterval <= 0)
  162. {
  163. OnOfflined();
  164. return;
  165. }
  166. }
  167. _heartBeatInterval--;
  168. }
  169. }
  170. if (!_stopped)
  171. {
  172. _waitEvent.WaitOne(TimeSpan.FromSeconds(_chechInterminal));
  173. if (!_stopped)
  174. {
  175. if (_chechInterminal == 0)
  176. {
  177. _chechInterminal = 3;
  178. }
  179. DoCheck();
  180. }
  181. }
  182. }
  183. private void OnOfflined()
  184. {
  185. Logger.WriteLineInfo($"ChatConnection keeper is offline");
  186. Offlined?.Invoke(this, EventArgs.Empty);
  187. }
  188. }
  189. }