最近发现webSocket连接,经常自动断开,看了晚上的一些文章,很多说是Nginx的问题,但是不想改Nginx因为怕影响其他系统,而且不一定有效,因此决定给webSocket加一个心跳机制:
1:先在服务端判断消息是不是心跳检测消息,是的话,原封不动将消息传给客户端即可:
if("heartCheck".equals(jsonObject.getString("heartCheck"))){// 心跳检测的消息
sendMessage(message);
return;
}
前端修改主要参考博客:https://blog.csdn.net/Real_Bird/article/details/77119897
分别在构造方法,onopen,onmessage,onclose三个方法中加上对应的心跳检测逻辑
constructor(props) {
super(props);
this.state = {
user: "",
visible: false,
messageOn: false,
messageCount: null
};
this.ws = new WebSocket(PATH_WEB_SOCKET + getUserName())
// 增加心跳检测--构造方法--start
this.ws.last_health_time = -1; // 上一次心跳时间
let thi = this;
this.ws.keepalive = function () {
let time = new Date().getTime();
if (thi.ws.last_health_time !== -1 && time - thi.ws.last_health_time > 200000) { // 不是刚开始连接并且连接大于200s
thi.ws.close()
} else {
// 如果断网了,ws.send会无法发送消息出去。ws.bufferedAmount不会为0。
if (thi.ws.bufferedAmount === 0 && thi.ws.readyState === 1) {
const sendJson = {
heartCheck: 'heartCheck',
user: getUserName()
};
thi.ws.send(JSON.stringify(sendJson));
thi.ws.last_health_time = time;
}
}
};
// 增加心跳检测--构造方法--end
this.goToPageMessage = this.goToPageMessage.bind(this);
this.setIsShown = this.setIsShown.bind(this);
this.setIsHide = this.setIsHide.bind(this);
}
componentDidMount(){
// 增加心跳检测--设置变量--start
let reconnect = 0; //重连的时间
let reconnectMark = false; //是否重连过
this.setState({
notificationSocket: true
});
// 增加心跳检测--设置变量--end
this.setState({
messageOn: true,
messageCount: 200
});
this.ws.onopen = ()=>{
console.log('web socket 已连接');
// 增加心跳检测--onopen--start
reconnect = 0;
reconnectMark = false;
this.ws.receiveMessageTimer = setTimeout(() => {
this.ws.close();
}, 300000); // 300s没收到信息,代表服务器出问题了,关闭连接。如果收到消息了,重置该定时器。
if (this.ws.readyState === 1) { // 为1表示连接处于open状态
this.ws.keepAliveTimer = setInterval(() => {
this.ws.keepalive();
}, 30000) // 30s
}
// 增加心跳检测--onopen--end
};
this.ws.onmessage = evt => {
// 增加心跳检测--onmessage --start
console.log("message", evt);
const message = JSON.parse(evt.data);
//console.log('message', message);
if("heartCheck" === message.heartCheck){
// 收到的是心跳检测消息
}else{
// 收到的是业务消息
}
// 收到消息,重置定时器
clearTimeout(this.ws.receiveMessageTimer);
this.ws.receiveMessageTimer = setTimeout(() => {
this.ws.close();
}, 300000); // 300s没收到信息,代表服务器出问题了,关闭连接。
// 增加心跳检测--onmessage --end
};
this.ws.onclose = ()=>{
console.log('web socket 已断开链接');
// 增加心跳检测--onclose--start
clearTimeout(this.ws.receiveMessageTimer);
clearInterval(this.ws.keepAliveTimer);
if (!reconnectMark) { // 如果没有重连过,进行重连。
reconnect = new Date().getTime();
reconnectMark = true;
}
let tempWs = this.ws; // 保存ws对象
if (new Date().getTime() - reconnect >= 180000) { // 180秒中重连,连不上就不连了
this.ws.close();
} else {
this.ws = new WebSocket(PATH_WEB_SOCKET + getUserName());
this.ws.onopen = tempWs.onopen;
this.ws.onmessage = tempWs.onmessage;
this.ws.onerror = tempWs.onerror;
this.ws.onclose = tempWs.onclose;
this.ws.keepalive = tempWs.keepalive;
this.ws.last_health_time = -1;
}
// 增加心跳检测--onclose--end
}
}
与此同时webSocket还有另外一个问题,也已经解决,请见博客:
The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method 已解决