背景:js中的websocket想要实现自动重连功能,由于js中只需要充当客户端收数据的功能,不需要发送数据,也就没有考虑实现心跳包。
var lockReconnect = false;//websocket连接状态,避免重复连接
$(document).ready(function () {
var ws = new WebSocket('ws://127.0.0.1:8000');
ws.onmessage = function(event){
//获取到的数据
}
ws.onclose = function (event){
console.log("---close---");
reconnect();
}
ws.onerror = function (event){
console.log("---error---");
reconnect();
}
});
function reconnect(){
if(lockReconnect) return;
lockReconnect = true;
setTimeout(function (){
setWebsocket();
lockReconnect = false;
}, 2000);//断开后2s自动重连
}