websocket连接成功后,会立刻监听到连接关闭的事件?
websocket主逻辑代码 handleSocketTask() {
let socketTask = wx.connectSocket({
url: 'wss://xxxxxxxx.com',
success: () => {
console.log('websocket 连接成功');
},
});
socketTask.onOpen(() => {
socketTask.send({
data: JSON.stringify({ check_data: this.data.checkData }),
success: (result) => {
console.log('socketTask send success', result);
},
fail: (error) => {
console.log('socketTask send fail', error);
},
});
});
socketTask.onMessage((data) => {
console.log('收到服务器消息: ', data, ' ', util.formatTime(new Date()));
const response = JSON.parse(data.data);
if (response.code == 0 && response.data.flag == '1') {
this.setData({
ciphertext: response.data.card_no,
});
}
});
socketTask.onError((errMsg) => {
console.log('socketTask onError result ', errMsg);
});
socketTask.onClose((result) => {
console.log('socketTask onClose result ', result);
this.setData({
ciphertext: '',
});
if (result.code == 99999) {
this.setData({
activeDisconnect: true,
});
}
// 如果还在当前页面,弹出提示框刷新二维码
if (!this.data.activeDisconnect) {
Dialog.alert({
message: '二维码已过期,请重新进入页面',
}).then(() => {
wx.navigateTo({
url: '../index/index',
});
});
}
});
this.data.socket = socketTask;
},
// 关闭 websocket 连接
closeSocketTask() {
this.data.socket.close({
code: 1000,
reason: '离开页面关闭 websocket 连接',
success: (res) => {
console.log('关闭 websocket 连接成功', res);
},
fail: (err) => {
console.log('关闭 websocket 连接失败', err);
},
});
},
// 隐藏页面时关闭 websocket 连接
onHide() {
this.setData({
activeDisconnect: true,
});
this.closeSocketTask();
},
// 页面卸载时关闭 websocket 连接
onUnload() {
this.setData({
activeDisconnect: true,
});
this.closeSocketTask();
},
运行结果如下: [图片] 为什么连接成功之后会立刻监听到 `onClose` 事件呢