9月25
项目要做一个后台消息推送,在测试过程中,发现每隔1分半自由,WebSocket会走OnError方法,将异常抛出,异常是java.io.EOFException.然后走@OnClose方法,将连接自动关闭,首先需要加上心跳,并且将nginx中加上proxy_read_timeout 设置为 2000s。
heartCheckFun(){
var that = this;
//心跳检测,每20s心跳一次
that.heartCheck = {
timeout: 20000,
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
that.websocketSend("HeartBeat");
console.info("客户端发送心跳");
self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
that.websock.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}
},
nginx的设置为:
location /{
proxy_pass http://xx.xxx.xxx.xx:xxxx;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 2000s;
keepalive_timeout 2000s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
尽管设置2000s,但是当到达设置时间,如果websocket没有进行通讯,还是会断开连接.可以前端做一个心跳检测,每隔20秒钟发起一次通信就行.
希望能帮到你;
heartCheckFun(){
var that = this;
//心跳检测,每20s心跳一次
that.heartCheck = {
timeout: 20000,
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
that.websocketSend("HeartBeat");
console.info("客户端发送心跳");
self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
that.websock.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}
},
nginx的设置为:
location /{
proxy_pass http://xx.xxx.xxx.xx:xxxx;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 2000s;
keepalive_timeout 2000s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
尽管设置2000s,但是当到达设置时间,如果websocket没有进行通讯,还是会断开连接.可以前端做一个心跳检测,每隔20秒钟发起一次通信就行.
希望能帮到你;




