Files
aida_front/src/tool/webSocket.js
2024-10-03 14:16:23 +08:00

79 lines
1.7 KiB
JavaScript

import { setCookie, getCookie, WriteCookie,clonAllCookie } from "@/tool/cookie";
import MyEvent from "@/tool/myEvents";
class MyWs {
constructor() {
this.ws = null;
// this.ws = new WebSocket();
let http = process.env.VUE_APP_BASE_URL.replace(/^https?:\/\//, '')
this.messageUrl = http+'/notification'
this.wsUrl = ''
this.reconnectionTime = null
}
linkWs(url) {
if(!(JSON.parse(getCookie("userInfo"))))return
if (this.ws && this.ws.readyState == 1) return
if(!this.wsUrl)this.wsUrl = url +`/${JSON.parse(getCookie("userInfo")).userId}`
this.ws = new WebSocket(this.wsUrl)
this.ws.onmessage = (e)=>{
try {
MyWs.receiveText(JSON.parse(e.data))
} catch (error) {
console.error('websocket',error)
}
}
this.ws.onclose = (e)=>{
console.log('',e);
console.log('错误');
this.reconnection()
}
this.ws.onerror = (e)=>{
console.log('失败',e);
this.reconnection()
}
}
reconnection(){
clearTimeout(this.reconnectionTime)
this.reconnectionTime = setTimeout(()=>{
this.linkWs(this.wsUrl)
},1000)
}
static receiveText(data,call){
MyEvent.emit('getMessage',data)
}
sendMessage(data) {
if (this.ws && this.ws.readyState == 1) {
let obj = {
cmd: 1,
data: {
name: '123',
}
}
this.send(obj)
obj = {
cmd: 4,
data: {
msg: data,
}
}
this.send(obj)
// obj = {
// cmd: 6,
// data: {
// msg: data,
// }
// }
// this.send(obj,this.ws)
}
}
send(obj) {
this.ws.send(JSON.stringify(obj))
}
close(){
if (this.ws && this.ws.readyState == 1) {
console.log("客户端 连接已关闭")
this.ws.close()
}
}
}
export default new MyWs()