1. 在mounted中调用方法
mounted() {
this.$nextTick(() => {
setTimeout(()=>{
this.startCommunication()
},300)
})
},
2.在方法中开始连接websocket
startCommunication() {
// 尝试 WebSocket连接
this.socket = uni.connectSocket({
url: "ws://xxx.xxx.x.xx:xxxx/地址", // 服务器地址
success(data) {
console.log("websocket连接成功");
},
})
//监听 WebSocket 连接打开事件
this.socket.onOpen(()=>{
console.log('WebSocket连接已打开!');
const data = {
sendid: uni.getStorageSync("userId"), // 登录人的id
};
const data1 = JSON.stringify(data)
// 通过 WebSocket 连接发送数据
this.socket.send({
data:data1
})
})
//监听 WebSocket 接受到服务器的消息事件
this.socket.onMessage((res)=>{
console.log("收到消息了");
if (res.data.indexOf("id") >= 0) {
let obj = JSON.parse(res.data)
// 提示弹框
new Dialog().show({
title: obj.Title,
titleColor: '#e6a23c',
confirmText: '确定',
content: obj.Content,
showCancel: true,
confirm: () => {
getMessage(obj.id).then(res => {
if (res.data.data.message?.isOk) {
uni.showToast({
title: '已读',
icon: "success",
})
} else {
uni.showToast({
title: '失败'
icon: "error",
})
}
})
},
cancel: () => {
console.log("我取消了哦");
}
})
}
})
// 监听 WebSocket 连接关闭事件
this.socket.onClose(({code})=>{
console.log("连接关闭事件",code);
})
// 监听 WebSocket 错误事件
this.socket.onError((errMsg)=>{
console.log(errMsg,'websocket发生错误');
// 连接出现错误后,可以进行重连
this.reconnect()
})
},
reconnect(){
setTimeout(() => {
this.startCommunication()
},1000)
},
3.组件销毁时需要关闭websocket
beforeDestroy() {
// 实例销毁,关闭socket
this.socket.close()
},