WebSocketHeartbeatPlugin.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //------------------------------------------------------------------------------
  2. // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有
  3. // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权
  4. // CSDN博客:https://blog.csdn.net/qq_40374647
  5. // 哔哩哔哩视频:https://space.bilibili.com/94253567
  6. // Gitee源代码仓库:https://gitee.com/RRQM_Home
  7. // Github源代码仓库:https://github.com/RRQM
  8. // API首页:https://www.yuque.com/rrqm/touchsocket/index
  9. // 交流QQ群:234762506
  10. // 感谢您的下载和使用
  11. //------------------------------------------------------------------------------
  12. //------------------------------------------------------------------------------
  13. using System;
  14. using System.Threading;
  15. using TouchSocket.Core;
  16. using TouchSocket.Sockets;
  17. namespace TouchSocket.Http.WebSockets
  18. {
  19. /// <summary>
  20. /// WebSocketHeartbeatPlugin
  21. /// </summary>
  22. [SingletonPlugin]
  23. public class WebSocketHeartbeatPlugin : WebSocketPluginBase
  24. {
  25. private TimeSpan m_timeTick=TimeSpan.FromSeconds(5);
  26. /// <summary>
  27. /// 初始化一个适用于WebSocket的心跳插件
  28. /// </summary>
  29. public WebSocketHeartbeatPlugin()
  30. {
  31. }
  32. /// <summary>
  33. /// 设置心跳间隔,默认5秒。
  34. /// </summary>
  35. /// <param name="timeSpan"></param>
  36. public void Tick(TimeSpan timeSpan)
  37. {
  38. this.m_timeTick = timeSpan;
  39. }
  40. /// <summary>
  41. /// <inheritdoc/>
  42. /// </summary>
  43. /// <param name="client"></param>
  44. /// <param name="e"></param>
  45. protected override void OnHandshaked(ITcpClientBase client, HttpContextEventArgs e)
  46. {
  47. if (client is HttpClientBase httpClientBase)
  48. {
  49. if (client.GetValue<Timer>(WebSocketExtensions.HeartbeatTimerProperty) is Timer timer)
  50. {
  51. timer.Dispose();
  52. }
  53. client.SetValue(WebSocketExtensions.HeartbeatTimerProperty, new Timer((o) =>
  54. {
  55. httpClientBase.PingWS();
  56. }, null, m_timeTick, m_timeTick));
  57. }
  58. base.OnHandshaked(client, e);
  59. }
  60. /// <summary>
  61. /// <inheritdoc/>
  62. /// </summary>
  63. /// <param name="client"></param>
  64. /// <param name="e"></param>
  65. protected override void OnDisconnected(ITcpClientBase client, DisconnectEventArgs e)
  66. {
  67. base.OnDisconnected(client, e);
  68. if (client.GetValue(WebSocketExtensions.HeartbeatTimerProperty) is Timer timer)
  69. {
  70. timer.SafeDispose();
  71. client.SetValue(WebSocketExtensions.HeartbeatTimerProperty, null);
  72. }
  73. }
  74. }
  75. }