1

websoket

  1. WebSocket在web端不会掉线;
  2. WebSocket在移动端会有很多种场景导致连接会断开,所以需要实现一个websocket断开与重连的功能;
  3. Websocket需要与后台实现一个ping,pong的心跳保持,用于监测服务器是否已经断开连接;

websocket建立

var host = getRootPath_dc().replace("http", "ws")+"/mediashow/mediasocket"; //声明host注意:是ws协议
console.log(host);
function getRootPath_dc() {
    var pathName = window.location.pathname.substring(1);
    var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
    if (webName == "") {
        return window.location.protocol + '//' + window.location.host;
    }
    else {
        return window.location.protocol + '//' + window.location.host + '/' + webName;
    }
}

//声明一个对开连接,关闭socket方法
function quit() {
    console.log("Goodbye!");
    socket.close();
    socket = null;
}
//声明一个socket
var socket;
//初始化方法
function initSocket() {
    console.log("websocket: "+host);
    try {
        socket = new WebSocket(host); //新创建一个socket对象
        console.log('WebSocket - status ' + socket.readyState); //将连接的状态信息显示在log
        socket.onopen = function(msg) {
            console.log("Welcome - status " + this.readyState);
        }; //监听打开连接
        //监听当接收信息时触发匿名函数
        socket.onmessage = function(msg) {
            console.log(msg.data);
            var json = msg.data;
            try{
                json = eval("(" + msg.data + ")");
            }catch(e){
            }
            //todo....
        };
        socket.onclose = function(e) {
            console.log("websocket失去连接 - status " + this.readyState);
            console.log(e)
            console.log("正在重连websocket");
            initSocket();
//            setTimeout(function(){
//            }, 2000);
        }; //关闭连接
    } catch (ex) {
        console.log(ex);
    }
}
initSocket();//调用

js文件可以加上定时器,心跳包

window.setInterval(function(){ //每隔1分钟发送一次心跳,避免websocket连接因超时而自动断开
    var ping = {"type":"ping"};
    socket.send(JSON.stringify(ping));
},1000*60);

diuren1205
57 声望5 粉丝

I love coding