1.websocket.js 文件
import wxToken from "./wxToken";
import { wxToast } from "./wxUai";
let token = wxToken.getToken()
token = token.split(' ')[1]
class websocket {
static getInstance(option) {
if (!this.socketTask) {
this.socketTask = new websocket(option)
}
return this.socketTask;
}
constructor(option) {
if(!option.url){
return wxToast.toast("参数url为必填项,请填写websocket链接地址");
}
this.option = option
this.initWebsocket(option)
}
initWebsocket({
url
}) {
this.socketTask = wx.connectSocket({
url: url
})
console.log(this.socketTask)
this.socketTask.onOpen((e) => {
console.log("打开链接")
this.heartCheck()
this.socketTask.onMessage((e) => {
this.onMessage(e)
})
})
this.socketTask.onClose((e) => {
this.onClose(e)
})
this.socketTask.onError((e) => {
this.onError(e)
})
}
/**
* 监听 WebSocket 连接关闭事件
*/
onClose(e) {
console.log('关闭:', e)
}
onMessage(e) {};
/**
* 监听 WebSocket 错误事件
*/
onError(e) {
console.log("链接错误", e)
}
/**
* 心跳检测
*/
heartCheck() {
let that = this;
this.interval = setInterval(() => {
this.socketTask.send({
data: JSON.stringify({
event: "ping"
}),
success(res) {
console.log(that.socketTask)
console.log("心跳", res)
},
fail(e) {
clearInterval(that.interval)
console.log("心跳失败", e)
}
})
}, 3000)
}
/**
* 发送消息
* @param {*} option
*/
send(option) {
let jsonOption = JSON.stringify(option)
this.socketTask.send(jsonOption)
}
/**
* 关闭
*/
close() {
console.log('关闭')
this.socketTask.close()
}
}
export const myWebsocket = websocket.getInstance({url:".../ws-chat?token=" + token})
1.1 url 填写 wss:// 开头的链接地址
2.页面引用
import { myWebsocket } from "../../utils/websocket"
Page({
onLoad(){
myWebsocket.onMessage=(data)=>{
console.log("index",data)
}
}
})