首先先封装一份websocket.js文件
class websocket{
constructor(url, time) {
this.is_open_socket = false //避免重复连接
this.url = url //地址
this.data = null
//心跳检测
this.timeout = time //多少秒执行检测
this.heartbeatInterval = null //检测服务器端是否还活着
this.reconnectTimeOut = null //重连之后多久再次重连
try {
return this.connectSocketInit()
} catch (e) {
this.is_open_socket = false
this.reconnect();
}
}
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit() {
if(uni.getStorageSync('userinfo')==null){
var uid=0
}else{
var uid= uni.getStorageSync('userinfo').id
}
this.socketTask = uni.connectSocket({
url: this.url,
header: {
'token':uid
},
success: () => {
console.log("正准备建立websocket中...");
// 返回实例
return this.socketTask
},
});
this.socketTask.onOpen((res) => {
console.log("WebSocket连接正常