Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

怎么在这个websocket添加心跳,使它断开后会自动重连?

vue封装websocket的js文件,如下:
var webSocket = null;
var globalCallback = null;//定义外部接收数据的回调函数

//初始化websocket
function initWebSocket(url) {

if ("WebSocket" in window) {
    webSocket = new WebSocket(url);//创建socket对象
    console.log(webSocket);
} else {
    alert("该浏览器不支持websocket!");
}
//打开
webSocket.onopen = function() {
    webSocketOpen();
};
//收信
webSocket.onmessage = function(e) {
    webSocketOnMessage(e);
    // console.log("eeeeee", e);
};
//关闭
webSocket.onclose = function() {
    webSocketClose();
    // setTimeout(() => {
    //     initWebSocket();
    // }, 1000);
};
//连接发生错误的回调方法
webSocket.onerror = function() {
    console.log("WebSocket连接发生错误");
};

}

//连接socket建立时触发
function webSocketOpen() {

//在此次定义好需要传过去的数据,先发送一个数据过去,data为与后端协议的数据类型
const data = {
    type: "CONNECT",
    // token: sessionStorage.getItem("token") || ""
    token: localStorage.getItem("token") || ""
};
sendSock(data, function() {});//调用发送数据的函数
console.log("WebSocket连接成功");

}

//客户端接收服务端数据时触发,e为接受的数据对象
function webSocketOnMessage(e) {

// const data = JSON.parse(e.data);//根据自己的需要对接收到的数据进行格式化
const data = e.data;
console.log("e.dataaaaa", data);
globalCallback(data);//将data传给在外定义的接收数据的函数,至关重要。
/*在此函数中还可以继续根据项目需求来写其他东西。 比如项目里需要根据接收的数据来判断用户登录是否失效了,此时需要关闭此连接,跳转到登录页去。*/

}

//发送数据
function webSocketSend(data) {

// console.log("e.data>>>", data);
// webSocket.send(JSON.stringify(data));//在这里根据自己的需要转换数据格式
webSocket.send(data);//在这里根据自己的需要转换数据格式

}

//关闭socket
function webSocketClose() {

//建立了多个socket,就做了一些判断。
if (
    webSocket.readyState === 1 &&
    webSocket.url === "ws://1xx.xx.xx.xxx:8088/ws"
) {
    webSocket.close();//这句话是关键,一直没有真正的关闭socket
    console.log("对话连接已关闭");
}

}

//在其他需要socket地方调用的函数,用来发送数据及接受数据
function sendSock(sendData,callback) {

// debugger;
globalCallback = callback;//此callback为在其他地方调用时定义的接收socket数据的函数,此关重要。
//此处先判断socket连接状态
//下面的判断主要是考虑到socket连接可能中断或者其他的因素,可以重新发送此条消息。
switch (webSocket.readyState) {
//CONNECTING:值为0,表示正在连接。
case webSocket.CONNECTING:
    setTimeout(function() {
        webSocketSend(sendData,callback);
    }, 1000);
    break;
    //OPEN:值为1,表示连接成功,可以通信了。
case webSocket.OPEN:
    webSocketSend(sendData);
    break;
    //CLOSING:值为2,表示连接正在关闭。
case webSocket.CLOSING:
    setTimeout(function() {
        webSocketSend(sendData,callback);
    }, 1000);
    break;
    //CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
case webSocket.CLOSED:
    // do something
    break;
default:
    // this never happens
    break;
}

}
//将初始化socket函数、发送(接收)数据的函数、关闭连接的函数export出去
export default {

initWebSocket,
webSocketClose,
sendSock,

};

在组件中调用,如下:
export default {

name: "eveAlarmBox",
data() {
    return {
        depId: '', //部门id
        wsUrl: "ws://199.116.433.255:8100/ws/msg.ws?type=alarm:0&depId=",
        wsType: "CONNECT",
        tableData: [],          
    };
},
created(){
    //获取用户登录的部门id
    let userInfo = localStorage.getItem('userInfo');
    this.depId = JSON.parse(userInfo).departmentid;
    this.socketApi.initWebSocket(this.wsUrl + this.depId);
    //data为和后端商量好的数据格式
     const data = {
         type: this.wsType,
         msg: "",
     };
    setTimeout(()=>{
        this.websocketSend(data);
    },1000);
},
methods:{
    // 接收socket回调函数返回数据的方法,服务端返回的数据
    getConfigResult(res) {
       this.tableData.push(JSON.parse(res));        
       this.$store.commit('websocket/PUSH_EVENT',   this.$store.commit('websocket/CHANGE_STATUS');//同步请求
    },
    websocketSend(data) {
    //data为要发送的数据,this.getConfigResult为回调函数,用于在此页面接收socket返回的数据。                
    
    this.socketApi.sendSock(data,this.getConfigResult);
     }, 

// beforeRouteLeave(to, from, next) {
//     //在离开此页面的时候主动关闭socket
//     this.socketApi.webSocketClose();
//     next();
// },

};

需求:怎么在这个websocket添加心跳,使它断开后会自动重连?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

断开重连是onClose里面调用初始化

心跳搞个setInterval定时send消息,主要是ping、pong


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...