今天后端websocket服务器出了问题,导致前端一直在提示net::ERR_CONNECTION_REFUSED。
1、原始代码
websocket连接的方法之前的代码:
deviceWebsocket () {
if ('WebSocket' in window) {
try {
// 报错提示在这一行
this.GOLBAL.websocket = new WebSocket('ws://120.79.132.29:8762/websocket/');
} catch (error) {
console.log(error);
};
} else {
alert('当前浏览器不支持websocket!项目无法正常运行');
return;
}
// 连接发生错误的回调方法
this.GOLBAL.websocket.onerror = () => {
this.$message.error({message: '获取实时数据失败,请稍后再试。'});
};
}
2、解决过程
因为这个websocket涉及到的功能很重要,必须在失败后进行重连,至少要让用户知道这个东西一直在尝试连接。然后网上找的都是这个错误怎么让它不出现,那都是后端的事,后端不解决,前端就只能干瞪眼了,那就自己动手吧。
但是异常捕获对这个错误也捕获不到,随后我想到这个触发websocket的onerror 方法,所以我考虑在onerror方法里添加失败重连的操作。
首先,我尝试用心跳重连的方式,也就是发送send方法来进行重连,结果会报错,此时websocket已经不能使用send方法了。
// 连接发生错误的回调方法
this.GOLBAL.websocket.onerror = () => {
this.$message.error({message: '获取实时数据失败,请稍后再试。'});
this.GOLBAL.websocket.send('心跳重连请求');
};
随后改变思路,尝试重新创建一个连接。这样是会重新进行连接,但是连接数量会越来越多,比如onerror事件触发后会触发多次,所以需要改进。
this.GOLBAL.websocket.onerror = () => {
this.$message.error({message: '获取实时数据失败,请稍后再试。'});
setTimeout(() => {
this.deviceWebsocket(); // 该方法为上面的websocket代码所在
}, 10000);
};
3、最终解决方案
每次重连之前调用close方法关闭之前的连接。如果更好的方式欢迎提出。
this.GOLBAL.websocket.onerror = () => {
this.$message.error({message: '获取实时数据失败,请稍后再试。'});
setTimeout(() => {
this.GOLBAL.websocket.close();
this.deviceWebsocket();
}, 10000);
};