当前位置:   article > 正文

webSocket的基本使用以及心跳检测、断线重连_websocket 重连

websocket 重连

前言

  为了获取实时数据,前端需要和后端保持通信,HTTP 协议只能是客户端向服务器发出请求,服务器返回查询结果。这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端要获知就非常麻烦。我们只能使用"轮询":每隔一段时候,就发出一个询问,了解服务器有没有新的信息。

webSoket心跳及重连机制

  websocket是前后端交互的长连接,在使用的过程中,遇到弱网或者网络暂时断连的情况时,服务端并没有触发onclose的事件,客户端也无法得知当前连接是否已经断开,服务端会继续向客户端发送多余链接,并且这些数据还会丢失。因此为了保证连接的可持续性和稳定性,我们需要有一套机制来检测客户端和服务端是否处于正常连接状态,websocket心跳重连就应运而生。

基本使用(详见websoketAPI官网The WebSocket API (WebSockets) - Web APIs | MDN (mozilla.org)

onopen()

实例对象的onopen属性,用于指定连接成功后的回调函数。

  1. ws.onopen = function () {
  2. ws.send('Hello Server!');
  3. }

如果要指定多个回调函数,可以使用addEventListener方法

ws.addEventListener('open', function (event) {ws.send('Hello Server!');});

webSoket.readyState方法

readyState属性返回实例对象的当前状态,共有四种。

  • CONNECTING:值为0,表示正在连接。

  • OPEN:值为1,表示连接成功,可以通信了。

  • CLOSING:值为2,表示连接正在关闭。

  • CLOSED:值为3,表示连接已经关闭,或者打开连接失败。

onerror方法

实例对象的onerror属性,用于指定报错时的回调函数。

onclose方法

实例对象的onclose属性,用于指定连接关闭后的回调函数。

onmessage方法

webSoket.send()

实例对象的send()方法用于向服务器发送数据。

webSoket.bufferedAmount

实例对象的bufferedAmount属性,表示还有多少字节的二进制数据没有发送出去。它可以用来判断发送是否结束。

整体代码

  1. <html>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>WebSocket Demo</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. // var ws = new WebSocket("wss://echo.websocket.org");
  9. /*
  10. ws.onerror = function(e) {
  11. console.log('已关闭');
  12. };
  13. ws.onopen = function(e) {
  14. console.log('握手成功');
  15. ws.send('123456789');
  16. }
  17. ws.onclose = function() {
  18. console.log('已关闭');
  19. }
  20. ws.onmessage = function(e) {
  21. console.log('收到消息');
  22. console.log(e);
  23. }
  24. */
  25. var lockReconnect = false;//避免重复连接
  26. var wsUrl = "wss://echo.websocket.org";
  27. var ws;
  28. var tt;
  29. function createWebSocket() {
  30. try {
  31. ws = new WebSocket(wsUrl);
  32. init();
  33. } catch(e) {
  34. console.log('catch');
  35. reconnect(wsUrl);
  36. }
  37. }
  38. function init() {
  39. ws.onclose = function () {
  40. console.log('链接关闭');
  41. reconnect(wsUrl);
  42. };
  43. ws.onerror = function() {
  44. console.log('发生异常了');
  45. reconnect(wsUrl);
  46. };
  47. ws.onopen = function () {
  48. //心跳检测重置
  49. heartCheck.start();
  50. };
  51. ws.onmessage = function (event) {
  52. //拿到任何消息都说明当前连接是正常的
  53. console.log('接收到消息');
  54. heartCheck.start();
  55. }
  56. }
  57. function reconnect(url) {
  58. if(lockReconnect) {
  59. return;
  60. };
  61. lockReconnect = true;
  62. //没连接上会一直重连,设置延迟避免请求过多
  63. tt && clearTimeout(tt);
  64. tt = setTimeout(function () {
  65. createWebSocket(url);
  66. lockReconnect = false;
  67. }, 4000);
  68. }
  69. //心跳检测
  70. var heartCheck = {
  71. timeout: 3000,
  72. timeoutObj: null,
  73. serverTimeoutObj: null,
  74. start: function(){
  75. console.log('start');
  76. var self = this;
  77. this.timeoutObj && clearTimeout(this.timeoutObj);
  78. this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
  79. this.timeoutObj = setTimeout(function(){
  80. //这里发送一个心跳,后端收到后,返回一个心跳消息,
  81. console.log('55555');
  82. ws.send("123456789");
  83. self.serverTimeoutObj = setTimeout(function() {
  84. console.log(111);
  85. console.log(ws);
  86. ws.close();
  87. // createWebSocket();
  88. }, self.timeout);
  89. }, this.timeout)
  90. }
  91. }
  92. createWebSocket(wsUrl);
  93. </script>
  94. </body>
  95. </html>

具体步骤

一、第一步页面初始化,先调用createWebSocket函数,目的是创建一个websocket的方法:new WebSocket(wsUrl)
  1. function createWebSocket() {
  2. try {
  3. ws = new WebSocket(wsUrl);
  4. init();
  5. } catch(e) {
  6. console.log('catch');
  7. reconnect(wsUrl);
  8. }
  9. }
二、第二步调用init方法,该方法内把一些监听事件封装如下:
当网络断开的时候,会先调用onerror,onclose事件可以监听到,会调用reconnect方法进行重连操作。正常的情况下,是先调用onopen方法的,当接收到数据时,会被onmessage事件监听到。
  1. function init() {
  2. ws.onclose = function () {
  3. console.log('链接关闭');
  4. reconnect(wsUrl);
  5. };
  6. ws.onerror = function() {
  7. console.log('发生异常了');
  8. reconnect(wsUrl);
  9. };
  10. ws.onopen = function () {
  11. //心跳检测重置
  12. heartCheck.start();
  13. };
  14. ws.onmessage = function (event) {
  15. //拿到任何消息都说明当前连接是正常的
  16. console.log('接收到消息');
  17. heartCheck.start();
  18. }
  19. }
三、重连操作 reconnect代码如下:
如果网络断开的话,会执行reconnect方法,使用了一个定时器,4秒后会重新创建一个新的websocket链接,重新调用createWebSocket函数,重新会执行及发送数据给服务器端。
  1. var lockReconnect = false;//避免重复连接
  2. function reconnect(url) {
  3. if(lockReconnect) {
  4. return;
  5. };
  6. lockReconnect = true;
  7. //没连接上会一直重连,设置延迟避免请求过多
  8. tt && clearTimeout(tt);
  9. tt = setTimeout(function () {
  10. createWebSocket(url);
  11. lockReconnect = false;
  12. }, 4000);
  13. }
四、心跳检测
  1. //心跳检测
  2. var heartCheck = {
  3. timeout: 3000,
  4. timeoutObj: null,
  5. serverTimeoutObj: null,
  6. start: function(){
  7. console.log('start');
  8. var self = this;
  9. this.timeoutObj && clearTimeout(this.timeoutObj);
  10. this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
  11. this.timeoutObj = setTimeout(function(){
  12. //这里发送一个心跳,后端收到后,返回一个心跳消息,
  13. //onmessage拿到返回的心跳就说明连接正常
  14. console.log('55555');
  15. ws.send("123456789");
  16. self.serverTimeoutObj = setTimeout(function() {
  17. console.log(111);
  18. console.log(ws);
  19. ws.close();
  20. // createWebSocket();
  21. }, self.timeout);
  22. }, this.timeout)
  23. }
  24. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号