Files
aida_front/src/tool/webSocket.js
X1627315083 4a65772ca9 fix
2024-12-18 17:38:43 +08:00

94 lines
2.0 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
this.times = 0
this.sendPINGTime = 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 {
let rv = JSON.parse(e.data)
if(rv == "PONG")return
this.times = 0
MyWs.receiveText(rv)
} catch (error) {
console.error('websocket',error)
}
}
clearInterval(this.sendPINGTime)
this.sendPINGTime = setInterval(()=>{
this.send({text:'PING'})
// },1000)
},1000*60*2)
this.ws.onclose = (e)=>{
this.reconnection()
}
this.ws.onerror = (e)=>{
this.reconnection()
}
}
reconnection(){
this.times++
clearTimeout(this.reconnectionTime)
if(this.times>=10)return
clearInterval(this.sendPINGTime)
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) {
if(this.ws.readyState == 1){
this.ws.send(JSON.stringify(obj))
}else{
clearTimeout(this.sendPINGTime)
this.reconnection()
}
}
close(){
if (this.ws && this.ws.readyState == 1) {
console.log("客户端 连接已关闭")
this.ws.close()
}
}
}
export default new MyWs()