html5 websocket掉线重连的解决办法

方法一
ReconnectingWebSocket 是一个小型的 JavaScript 库,封装了 WebSocket API 提供了在连接断开时自动重连的机制。
开源
https://github.com/joewalnes/reconnecting-websocket
只需要简单的将:
ws = new WebSocket('ws://host:port');
替换成:
ws = new ReconnectingWebSocket('ws://host:port');

方法二
非常严格的解决 webSocket 重连,包括网络断线后重连的解决方法:
1、websocket 重连的脚本(reconnecting-websocket.js):
https://github.com/joewalnes/reconnecting-websocket
2、监听网络状态的脚本(offline.js):
https://github.com/hubspot/offline
3、页面引用:上述脚本
4、JavaScript 示例

var socketStatus=false;
function tanchuang(){
    Offline.check();
    if(!socketStatus){
        $('.big_toast div').html('网络连接已断开!');
        $('.big_toast').css('left', '45%');
        $('.big_toast').fadeIn("fast");
        $('.big_toast').fadeOut(2000);
        if(Offline.state === 'up' && websocket.reconnectAttempts>websocket.maxReconnectInterval){
            window.location.reload();
        }
    //    buildSocket();
    }else{
        websocket.send("{}");
    }
}
var websocket;
buildSocket();
function buildSocket(){
        if ('WebSocket' in window) {      
            websocket = new ReconnectingWebSocket("ws://http://www.phpernote.com/websocket/get/overview");
        } else if ('MozWebSocket' in window) {
            //   websocket = new MozWebSocket("ws://http://www.phpernote.com/websocket/get/all/data/rt");
            websocket = new MozWebSocket("ws://http://www.phpernote.com/websocket/get/overview");
        } else {
            //   websocket = new SockJS("http://www.phpernote.com/sockjs/websocket/get/all/data/rt");
            websocket = new SockJS("http://host/websocket/get/overview");
                     
        }
        
}
websocket.onopen = function (evnt) {
    socketStatus=true;
    clearInterval(t1);//去掉定时器
    t2=setInterval(tanchuang,3000);
    // tanchuang();
};
websocket.onmessage = function (evnt) {
};
websocket.onerror = function (evnt) {
    socketStatus=false;
};
websocket.onclose = function (evnt) {
    socketStatus=false;
};

当网络断开连接后,会先重连3000次,如果3000次重连不上则浏览器放弃重连,开始监听网络状态,如果网络一恢复,则直接刷新页面,恢复数据正常。
转自
本文永久地址:http://www.phpernote.com/html5/1370.html

点赞