websockect连接成功后readyState却持续6秒内还是0,目前应如何判断ws是否连接成功
我们的小程序保障ws连接的机制是:每6秒会发送一次心跳,如果发送心跳成功后判断该ws的readyState同时为1,则断定为ws是连通的,如果发送失败,或发送成功但是readyState不为1则都算失败,将会关闭ws,重新发起连接。
后台日志(下方代码块),以及小程序实时日志(下方截图)可看出客户在16:52::18(小程序后台日志16:52::17秒)成功连接,readystate不等于1并在6秒内仍不为,故在下一次心跳则断开重连。
{
"timestamp" : "2020-05-11T16:52:18.531+08",
"level" : "INFO",
"thread" : "nioEventLoopGroup-3-2",
"logger" : "websocket",
"message" : "医生端小程序已连接, currentDoctor: CurrentDoctor{userId=1059}, ChannelId: 00163efffe0dd1cc-00007c72-0003436c-a07c3fec4a4defde-fd860c6a",
"context" : "default"
}{
"timestamp" : "2020-05-11T16:52:24.306+08",
"level" : "INFO",
"thread" : "nioEventLoopGroup-3-2",
"logger" : "heartbeat",
"message" : "接收客户端心跳, HB: HB_2fd7016c-b1d5-467b-b537-7f0cecdcee35, ChannelId: 00163efffe0dd1cc-00007c72-0003436c-a07c3fec4a4defde-fd860c6a",
"context" : "default"
}{
"timestamp" : "2020-05-11T16:52:24.391+08",
"level" : "WARN",
"thread" : "nioEventLoopGroup-3-2",
"logger" : "websocket",
"message" : "医生端小程序已断开, currentDoctor: CurrentDoctor{userId=1059}, ChannelId: 00163efffe0dd1cc-00007c72-0003436c-a07c3fec4a4defde-fd860c6a",
"context" : "default"
}
心跳代码
// 心跳定时器启动
startHBTimer () {
clearInterval(this._timer)
this._timer = setInterval(() => {
this.sendHBMsg()
}, 6000)
}
// 发送心跳
sendHBMsg () {
let self = this
const loginInfo = wx.getStorageSync('loginInfo')
if (!loginInfo) { return }
self._socketTask.send({
data: `HB_${loginInfo.token}_${loginInfo.name}`,
success: (e) => {
if (self._socketTask.readyState * 1 === 1) {
wx.hideNavigationBarLoading()
} else {
self.sendFailHandler(self)
wxLog.warn('sendHBMsg success but readyStateCode is not open', '&readyStateCode=' + self._socketTask.readyState + '&device=' + JSON.stringify(wx.getStorageSync('systemDetailInfo')))
}
},
fail: (res) => {
self.sendFailHandler(self)
wxLog.warn(res, 'sendHBMsg fail&readyStateCode=' + self._socketTask.readyState + '&device=' + JSON.stringify(wx.getStorageSync('systemDetailInfo')))
}
})
}
sendFailHandler (self) {
wx.showNavigationBarLoading()
self.createConnection()
}
目前readyState这个状态是不可用的状态吗?那客户端应如何判断ws是否连接成功状态