带心跳的websocket
作者:互联网
var wsServer = ws;
var limitConnect = 5; // 断线重连次数
var timeConnect = 0;
webSocketInit(wsServer);
console.log("websocket地址")
console.log(ws)
var codeList = []
var epcList = []
var tidList = []
//socket初始化
function webSocketInit(service) {
console.log("地址:" + service)
var ws = new WebSocket(service);
ws.onopen = function() {
console.log("已连接TCP服务器");
var data = {
type: "heartbeat",
data: "",
from: "touchpc"
}
ws.send(JSON.stringify(data))
};
ws.onmessage = function(msg) {
var data = $.parseJSON(msg.data);
if (data.type == "heartbeat") {
} else if (data.type == "pushbook") {
console.log("检索到的数据")
var result = $.parseJSON(msg.data).data
}
};
ws.onclose = function() {
console.log('服务器已经断开');
reconnect(service);
};
ws.onerror = function(err) {
console.log("服务器报错:");
reconnect(service);
};
// 重连
function reconnect(service) {
// lockReconnect加锁,防止onclose、onerror两次重连
if (limitConnect > 0) {
if (localStorage.getItem('lockReconnect') != true) {
localStorage.setItem("lockReconnect", 1);
limitConnect--;
timeConnect++;
console.log("第" + timeConnect + "次重连");
// 进行重连
setTimeout(function() {
webSocketInit(service);
localStorage.removeItem("lockReconnect");
}, 2000);
}
} else {
console.log("TCP连接已超时");
}
}
// 心跳 * 回应
setInterval(function() {
var data = {
type: "heartbeat",
data: "",
from: "touchpc"
}
ws.send(JSON.stringify(data))
// websocket.send(JSON.stringify(data));
}, 1000 * 100);
}
标签:function,console,log,var,ws,心跳,websocket,data 来源: https://blog.csdn.net/weixin_44419615/article/details/122595187