import { MessageWarning } from "./message";
import useMemberStore from "@/stores/member";
interface ISocket {
websocket: any;
connectURL: string;
reconnect_count: number;
reconnect_current: number;
reconnect_timer: any;
reconnect_interval: number;
stopWs: boolean;
init: (receiveMessage: Function | null, errorFun: Function | null) => any;
send: (data: any) => void;
close: () => void;
handleReconnect: () => void;
}
const socket: ISocket = {
websocket: null, //实例
connectURL: "", //地址
reconnect_timer: null, //重连timer
reconnect_count: 3, //最大重连次数
reconnect_current: 0, //已发起重连次数
reconnect_interval: 10000, //重连频率
stopWs: false, //彻底终止ws
// 初始化连接
init: (receiveMessage: Function | null, errorFun: Function | null) => {
if (!("WebSocket" in window)) {
MessageWarning("浏览器不支持WebDocket");
return;
}
if (socket.reconnect_current === 0) {
console.log("websocket", "初始化连接中...");
}
if (
socket.websocket &&
socket.websocket.readyState == socket.websocket.OPEN
) {
return;
}
const memberStore = useMemberStore();
if (!memberStore.token) return;
socket.websocket = new WebSocket(socket.connectURL, [memberStore.token]);
// 连接成功
socket.websocket.onopen = () => {
socket.stopWs = false;
// 重置重连尝试成功连接
socket.reconnect_current = 0;
console.log("websocke", "连接成功,等待数据推送...");
};
socket.websocket.onmessage = (e: any) => {
if (receiveMessage) {
receiveMessage(e);
}
};
socket.websocket.onclose = () => {
if (socket.reconnect_current === 0) {
console.log("websocket", "连接异常[onclose]...");
}
if (!socket.stopWs) {
socket.handleReconnect();
}
};
// 连接失败
socket.websocket.onerror = () => {
if (socket.reconnect_current === 0) {
console.log("websocket", "连接失败[onerror]...");
}
if (errorFun) errorFun(socket.websocket.readyState);
};
},
// 重连逻辑
handleReconnect: () => {
if (socket.reconnect_current < socket.reconnect_count) {
socket.reconnect_current++;
console.log("websocket", "尝试重连...");
socket.reconnect_timer = setTimeout(() => {
socket.init(null, null);
}, socket.reconnect_interval);
} else {
clearTimeout(socket.reconnect_timer);
console.log("wesocket", "最大重连失败,终止重连...");
}
},
// 消息发送
send: (data) => {
// 开启状态直接发送
if (
socket.websocket &&
socket.websocket.readyState === socket.websocket.OPEN
) {
socket.websocket.send(JSON.stringify(data));
} else {
console.error("websocket", "未连接");
}
},
// 关闭连接
close: () => {
if (socket.websocket) {
console.log("关闭websocket...");
socket.stopWs = true;
socket.websocket.close();
socket.websocket = null;
}
},
};
export default socket;
websocket在页面里使用
onMounted(()=>{
socket.connectURL = `${import.meta.env.VITE_WS_AI_CHAT}`;
await socket.init(receiveMessage, errorFun);
)
//处理接收的data
const receiveMessage = (message: any) => {
console.log(message.data)
};
//websocket 连接失败,关闭sriptloading
const errorFun = () => {
};