weixin_33670786 报错信息:
websocket 断开: 1002 An unrecoverable IOException occurred so the connection was closed
错误描述:
可以正常连接,但是只要发送消息(无论是心跳消息还是正常消息),都会断开连接
补充:
接口在websocket检测工具上,是可以正常收发消息的。但是运行到项目中就会报错
代码如下:
initWebSocket() {
var url = "wss://www.xxx/" + this.userId;
if ('WebSocket' in window) {
this.ws = new WebSocket(url);
} else if ('MozWebSocket' in window) {
this.ws = new MozWebSocket(url);
}
this.ws.onmessage = this.onmessage;
this.ws.onopen = this.onopen;
this.ws.onclose = this.onclose;
this.ws.onerror = this.onerror;
},
reconnect() { //重新连接
var that = this;
if (that.lockReconnect) {
return;
};
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(function() {
//新连接
that.initWebSocket();
that.lockReconnect = false;
}, 5000);
},
reset() { //重置心跳
var that = this;
//清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
//重启心跳
that.start();
},
start() { //开启心跳
console.log('开启心跳');
var self = this;
self.timeoutObj && clearTimeout(self.timeoutObj);
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
self.timeoutObj = setTimeout(function() {
if (self.ws.readyState == 1) { //如果连接正常
let params = {
To: self.userId,
message: "ping..."
};
self.ws.send(params) //这里发送一个心跳,后端收到后,返回一个心跳消息
} else { //否则重连
self.reconnect()
}
self.serverTimeoutObj = setTimeout(function() {
self.ws.close() //超时关闭
}, self.timeout)
}, self.timeout)
},
onopen() {
console.log("open")
this.start() //开启心跳
},
onmessage(e) {
if (e.data.message == 'ping...') {
console.info('接收到心跳消息') // 心跳消息,不作处理
} else {
const redata = e.data
if (redata.messageType == '加钟') {
this.addClockOrderList.push(redata.orderSn)
if (this.addClockOrderList.length > 0) {
this.matchingList()
}
}
}
this.reset(); //收到服务器信息,心跳重置
},
onclose(e) {
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
this.reconnect() //重连
},
onerror(e) {
console.log("出现错误")
this.reconnect() //重连
},
onsend(msg) {
this.ws.send(msg) //数据发送
},