最近、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には解決済みの別の問題があります。ブログを参照してください:
リモートエンドポイントは状態[TEXT_FULL_WRITING]にありました。これは、呼び出されたメソッド已解决に対して無効な状態です。