import config from "@/lib/config";
import { getLocalAdd, getToken } from "@/utils/auth";
import toolObj from '@/utils/toolObj';
const ZUUL_WS_PORT = ':' + ZUUL_PORT_WS
const userId = sessionStorage.getItem('userId')
let hstHead = window.location.href.split(":")[0];
export const getMyWebSocket = (modularName, callback) => {
let accessToken = getToken(),
localAdd = getLocalAdd(),
hst = config.ip.split(":")[0] + ZUUL_WS_PORT,
myWebsocket = null;
if (!accessToken) return false;
const uuid = toolObj.uuid()
console.log('uuid===', uuid);
let url = "ws://" + hst + "/websocket" + "?userId=" + userId + "&modularName=" + modularName + "&uuid=" + uuid;
if (hstHead === 'https') {
url = "wss://" + hst + "/websocket" + "?userId=" + userId + "&modularName=" + modularName + "&uuid=" + uuid;
}
const initSocket = () => {
myWebsocket = new WebSocket(url);
console.log(myWebsocket, "myWebsocket", hst, "hst");
};
initSocket();
//连接发生错误的回调方法
myWebsocket.onerror = () => {
console.log("WebSocket连接发生错误");
// clearInterval(sendTime);
callback('lose')
};
//连接成功建立的回调方法
myWebsocket.onopen = () => {
console.log("WebSocket连接成功");
myWebsocket.send("pong")
// clearInterval(sendTime);
/* myWebsocket.send(`{message:"cbb",To:"${userId}_index"}`)
sendTime = setInterval(() => {
myWebsocket.send(`{message:"cbb",To:"${userId}_index"}`)
}, 5000) */
};
//接收到消息的回调方法
myWebsocket.onmessage = function (event) {
console.log('接收到消息的回调方法event', event);
if (event.data !== 'ping') {
let data = JSON.parse(event.data)
console.log('data', data);
if (typeof callback === "function") {
callback(data);
}
}
};
//连接关闭的回调方法
myWebsocket.onclose = () => {
console.log("webSocket连接关闭!");
// myWebsocket = null
// clearInterval(sendTime);
};
return myWebsocket
};