You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.2 KiB
53 lines
1.2 KiB
|
3 months ago
|
let websocket: WebSocket;
|
||
|
|
const msgHandlersMap = {};
|
||
|
|
let lastUrl;
|
||
|
|
let closeFlag = false;
|
||
|
|
|
||
|
|
export const closeWebSocket = () => {
|
||
|
|
closeFlag = false;
|
||
|
|
websocket?.close();
|
||
|
|
};
|
||
|
|
|
||
|
|
export const sendSocketMsg = (msg) => {
|
||
|
|
websocket?.send(JSON.stringify(msg));
|
||
|
|
};
|
||
|
|
|
||
|
|
export const openWebSocket = (url) => {
|
||
|
|
if (websocket && websocket.readyState === WebSocket.OPEN) {
|
||
|
|
if (lastUrl == url) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
closeWebSocket();
|
||
|
|
}
|
||
|
|
websocket = new WebSocket(url);
|
||
|
|
lastUrl = url;
|
||
|
|
websocket.onopen = () => {
|
||
|
|
console.log('websocket已连接');
|
||
|
|
closeFlag = true;
|
||
|
|
};
|
||
|
|
websocket.onmessage = (msg) => {
|
||
|
|
const event = JSON.parse(msg.data);
|
||
|
|
const handlers = msgHandlersMap[event.type];
|
||
|
|
if (!handlers) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
Object.values(handlers).forEach((handler: any) => {
|
||
|
|
handler(event.data);
|
||
|
|
});
|
||
|
|
};
|
||
|
|
websocket.onclose = () => {
|
||
|
|
console.log('websocket已断开');
|
||
|
|
if (closeFlag) {
|
||
|
|
setTimeout(() => {
|
||
|
|
openWebSocket(url);
|
||
|
|
}, 2000);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
};
|
||
|
|
|
||
|
|
export const registerHandler = (type, key, handler) => {
|
||
|
|
const handlers = msgHandlersMap[type] || {};
|
||
|
|
handlers[key] = handler;
|
||
|
|
msgHandlersMap[type] = handlers;
|
||
|
|
};
|