当前位置:   article > 正文

websocket连接及心跳检测_网页端用户在线心跳检测

网页端用户在线心跳检测
  1. var websocket = null;
  2. var lockReconnect = false;
  3. /**
  4. * 初始化websocket连接
  5. */
  6. function initWebSocket() {
  7. webSocketInit();
  8. }
  9. /**
  10. * 连接ws
  11. */
  12. function webSocketInit(){
  13. try{
  14. if('WebSocket' in window) {
  15. websocket = new WebSocket(url); //url为websocket地址
  16. } else {
  17. alert("该浏览器不支持websocket!");
  18. }
  19. }catch (e){
  20. websocketReconnect(); //尝试重连websocket
  21. }
  22. websocket.onopen = function(event) {
  23. console.log("建立连接");
  24. }
  25. websocket.onclose = function(event) {
  26. console.log('连接关闭')
  27. lockReconnect = false;
  28. websocketReconnect(); //尝试重连websocket
  29. }
  30. //建立通信后,监听到后端的数据传递过来了
  31. websocket.onmessage = function(event) {
  32. heartCheck.start();
  33. }
  34. websocket.onerror = function() {
  35. //alert('websocket通信发生错误!');
  36. }
  37. window.onbeforeunload = function() {
  38. websocket.close();
  39. }
  40. }
  41. /**
  42. * 重连ws
  43. */
  44. function websocketReconnect(){
  45. if (lockReconnect) { // 是否已经执行重连
  46. return;
  47. };
  48. lockReconnect = true;
  49. //没连接上会一直重连,设置延迟避免请求过多
  50. tt && clearTimeout(tt);
  51. var tt = setTimeout(function () {
  52. webSocketInit();
  53. lockReconnect = false;
  54. console.log("正在重连");
  55. heartCheck.start();
  56. }, 5000)
  57. }
  58. //心跳检测
  59. var heartCheck = {
  60. timeout: 120000,
  61. timeoutObj: null,
  62. serverTimeoutObj: null,
  63. start: function () {
  64. console.log('start');
  65. var self = this;
  66. this.timeoutObj && clearTimeout(this.timeoutObj);
  67. this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
  68. this.timeoutObj = setTimeout(function () {
  69. //发送测试信息,后端收到后,返回一个消息,
  70. websocket.send('hello');
  71. self.serverTimeoutObj = setTimeout(function () {
  72. //websocket.close();
  73. }, self.timeout);
  74. }, this.timeout)
  75. }
  76. }
  77. /**
  78. * 发送ws消息
  79. */
  80. function sendWsMsgTimer(){
  81. console.log("发送消息");
  82. connectTimer = window.setInterval(function(){
  83. websocket.send('hello');
  84. },120000);
  85. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/242045
推荐阅读
相关标签
  

闽ICP备14008679号