websoket() {
console.log('初始化');
uni.connectSocket({
url: 'ws://192.168.1.111:19107/hand',
})
uni.onSocketOpen(function(res) {
uni.$u.toast('WebSocket连接已打开!')
});
uni.onSocketError(function(res) {
uni.$u.toast('WebSocket连接打开失败,请检查!')
});
},
jiexiaoxi() {
console.log('收到的消息');
uni.onSocketMessage(function(res) {
console.log('收到服务器内容:' + res.data);
})
},
async fasong() {
const params={
receiveUserid:'e68b0d11d077a4929f0333dd87f67c7e',
message:'测试'
}
const arr=await http.post('/api/chat/chatAdd',params)
console.log(arr);
},
shoucilianjie() {
setTimeout(()=>{
const data = {
"action": "init",
"chatMsg": {
"senderId": 'e68b0d11d077a4929f0333dd87f67c7e',
"receiverId": "",
"msg": ""
}
}
const msg = JSON.stringify(data)
console.log('登录发送');
uni.sendSocketMessage({
data: msg,
success:(res)=>{console.log(res)}
});
},100)
},
xintiao() {
setInterval(()=>{
const data = {
action: 'heartbeat'
}
const msg = JSON.stringify(data)
console.log('心跳');
uni.sendSocketMessage({
data: msg,
success:(res)=>{console.log(res)}
});
},10000)
},
执行顺序
this.websoket()先建立链接
this.shoucilianjie()建立后验证身份
this.xintiao()身份验证完毕后建立心跳
this.jiexiaoxi()最后接收消息
文章介绍了如何在UniApp中使用WebSocket进行实时通信,包括连接初始化、错误处理、消息发送和心跳检测。首先建立WebSocket链接,然后验证身份并发送心跳,最后接收服务器消息。
5250

被折叠的 条评论
为什么被折叠?



