Blogger Information
Blog 143
fans 1
comment 0
visits 440084
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
WebSocket掉线重连的解决办法
弘德誉曦的博客
Original
9641 people have browsed it

WebSocket掉线重连的解决办法(reconnecting-websocket.js的使用)

阅读文字大小:【小】   【大】    文章背景:            展开

html5 的 WebSocket 帮我们实现了长连接功能,但实际使用中发现 WebSocket 链接还是不是非常稳定的,经常自我掉线了,下面就分享两种方法解决一下这个问题。

方法一

ReconnectingWebSocket 是一个小型的 JavaScript 库,封装了 WebSocket API 提供了在连接断开时自动重连的机制。

只需要简单的将:

1ws = new WebSocket('ws://....');

替换成:

1ws = new ReconnectingWebSocket('ws://....');

websocket 重连的脚本下载地址:https://github.com/joewalnes/reconnecting-websocket

方法二

非常严格的解决 webSocket 重连,包括网络断线后重连的解决方法:

1、websocket 重连的脚本(reconnecting-websocket.js):

https://github.com/joewalnes/reconnecting-websocket

2、监听网络状态的脚本(offline.js):

https://github.com/hubspot/offline

3、页面引用:上述脚本

4、JavaScript demo

01var socketStatus=false;
02function tanchuang(){
03    Offline.check();
04    if(!socketStatus){
05        $('.big_toast div').html('网络连接已断开!');
06        $('.big_toast').css('left', '45%');
07        $('.big_toast').fadeIn("fast");
08        $('.big_toast').fadeOut(2000);
09        if(Offline.state === 'up' && websocket.reconnectAttempts>websocket.maxReconnectInterval){
10            window.location.reload();
11        }
12    //    buildSocket();
13    }else{
14        websocket.send("{}");
15    }
16}
17var websocket;
18buildSocket();
19function buildSocket(){
20        if ('WebSocket' in window) {     
21            websocket = new ReconnectingWebSocket("ws://http://www.phpernote.com/websocket/get/overview");
22        } else if ('MozWebSocket' in window) {
23            //   websocket = new MozWebSocket("ws://http://www.phpernote.com/websocket/get/all/data/rt");
24            websocket = new MozWebSocket("ws://http://www.phpernote.com/websocket/get/overview");
25        } else {
26            //   websocket = new SockJS("http://www.phpernote.com/sockjs/websocket/get/all/data/rt");
27            websocket = new SockJS("http://host/websocket/get/overview");
28                      
29        }
30         
31}
32websocket.onopen = function (evnt) {
33    socketStatus=true;
34    clearInterval(t1);//去掉定时器
35    t2=setInterval(tanchuang,3000);
36    // tanchuang();
37};
38websocket.onmessage = function (evnt) {
39};
40websocket.onerror = function (evnt) {
41    socketStatus=false;
42};
43websocket.onclose = function (evnt) {
44    socketStatus=false;
45};

最终的效果是:当网络断开连接后,会先重连3000次,如果3000次重连不上则浏览器放弃重连,开始监听网络状态,如果网络一恢复,则直接刷新页面,恢复数据正常。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post