2024-09-30 17:59:24 +08:00
|
|
|
import { setCookie, getCookie, WriteCookie,clonAllCookie } from "@/tool/cookie";
|
2024-08-19 10:36:46 +08:00
|
|
|
import MyEvent from "@/tool/myEvents";
|
2024-08-13 09:36:13 +08:00
|
|
|
class MyWs {
|
|
|
|
|
constructor() {
|
|
|
|
|
this.ws = null;
|
|
|
|
|
// this.ws = new WebSocket();
|
2024-08-19 10:36:46 +08:00
|
|
|
let http = process.env.VUE_APP_BASE_URL.replace(/^https?:\/\//, '')
|
|
|
|
|
this.messageUrl = http+'/notification'
|
2024-09-30 17:59:24 +08:00
|
|
|
this.wsUrl = ''
|
|
|
|
|
this.reconnectionTime = null
|
2024-08-13 09:36:13 +08:00
|
|
|
}
|
|
|
|
|
linkWs(url) {
|
|
|
|
|
if (this.ws && this.ws.readyState == 1) return
|
2024-09-30 17:59:24 +08:00
|
|
|
if(!this.wsUrl)this.wsUrl = url +`/${JSON.parse(getCookie("userInfo")).userId}`
|
|
|
|
|
this.ws = new WebSocket(this.wsUrl)
|
2024-08-19 10:36:46 +08:00
|
|
|
this.ws.onmessage = (e)=>{
|
|
|
|
|
try {
|
|
|
|
|
MyWs.receiveText(JSON.parse(e.data))
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('websocket',error)
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-09-30 17:59:24 +08:00
|
|
|
this.ws.onclose = (e)=>{
|
|
|
|
|
reconnection()
|
|
|
|
|
}
|
|
|
|
|
this.ws.onerror = (e)=>{
|
|
|
|
|
reconnection()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
reconnection(){
|
|
|
|
|
clearTimeout(this.reconnectionTime)
|
|
|
|
|
this.reconnectionTime = setTimeout(()=>{
|
|
|
|
|
this.linkWs(this.wsUrl)
|
|
|
|
|
},1000)
|
2024-08-19 10:36:46 +08:00
|
|
|
}
|
|
|
|
|
static receiveText(data,call){
|
|
|
|
|
MyEvent.emit('getMessage',data)
|
2024-08-13 09:36:13 +08:00
|
|
|
}
|
|
|
|
|
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) {
|
2024-10-01 10:33:44 +08:00
|
|
|
console.log("客户端 连接已关闭")
|
2024-08-13 09:36:13 +08:00
|
|
|
this.ws.close()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-08-19 10:36:46 +08:00
|
|
|
|
|
|
|
|
export default new MyWs()
|