uniapp で WebSocket を記述するには 2 つの方法があります。1 つはWebSocketで、もう 1 つはSocketTask です。
公式サイトへのリンクを貼っておきますが、公式サイトにはソケットの使い方が詳しく書かれています。
ウェブソケット:https://uniapp.dcloud.net.cn/api/request/websocket.html
ソケットタスク:uni-app公式サイト
では、2 つの方法のうちどちらを選択すればよいでしょうか?
私の個人的な理解は次のとおりです。
単一のページで使用していて、ソケット リンクが 1 つしかない場合は、WebSocket を使用できます。
複数のページまたは複数のソケット リンクでソケット操作を行う場合は、エラーが発生しにくいsocketTask フォームを使用することをお勧めします。
私自身が使用するときは、socketTask フォームを選択します。コードは次のとおりです。
//连接websocket
connectSocket() {
let that = this;
console.log('调用连接websocket')
this.socketTask = uni.connectSocket({
url: 'wss://x x x',
success(res) {
console.log("websocket连接成功");
// that.isSuccess = true
},
fail(err) {
console.log("报错", err);
}
},
);
this.socketTask.onOpen(function(res) {
console.log('WebSocket连接已打开!');
that.isSuccess = true
that.getStatus()
that.heart()
})
this.socketTask.onMessage(function(res) {
console.log('收到服务器内容:' + res.data);
that.handlerMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
});
this.socketTask.onError(function(res) {
console.log('WebSocket连接打开失败,请检查!');
console.log(res);
// this.isSuccess = false
// that.connectSocket()
//进入重新连接
that.reconnect();
})
// // 监听连接关闭 -
this.socketTask.onClose((e) => {
console.log('WebSocket连接关闭!');
clearInterval(that.timer)
that.timer = ''
if (!that.isClose) {
that.reconnect()
}
})
console.log(this.socketTask)
},
//进入重新连接
reconnect() {
console.log('进入断线重连');
// this.socketTask.close();
this.socketTask = null;
this.connectSocket()
},
//发送消息
sendSocketMessage(msg) {
console.log('发送信息')
console.log(msg)
return new Promise((reslove, reject) => {
this.socketTask.send({
data: msg,
success(res) {
console.log('发送成功')
reslove(res)
},
fail(res) {
console.log('发送失败')
console.log(res)
reject(res)
}
});
})
},
//心跳
heart() {
let that = this;
clearInterval(this.timer);
this.timer = '';
let msg = {
"type": "heartbeat",
}
this.timer = setInterval(() => {
that.sendSocketMessage(JSON.stringify(msg)).then(res => {
console.log('心跳成功')
}).catch(res => {
console.log('发送失败')
console.log((res))
})
}, 200000)
},
注意すべき点がいくつかあります。
1 - ハートビートの時間制限は、フロント エンドとバック エンドの間でネゴシエートされます。ハートビートは、WebSocket が常にリンク状態になるようにするために存在するため、ソケットを閉じる場合は、メモリ リークや無駄を避けるためにハートビートを忘れずにクリアしてください。
2 - 再接続 ここでは、リンクを再接続する必要がある場合とリンクを閉じる必要がある場合を示すフラグを設定できます。