一个全随机的刷装备小游戏
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.

39 lines
938 B

let websocket: WebSocket;
const msgHandlersMap = {};
let lastUrl;
export const openWebSocket = (url) => {
if (websocket && websocket.readyState === WebSocket.OPEN) {
if (lastUrl == url) {
return;
}
websocket.close();
}
websocket = new WebSocket(url);
lastUrl = url;
websocket.onopen = () => {
console.log('websocket已连接');
};
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已断开');
setTimeout(() => {
openWebSocket(url);
}, 2000);
};
};
export const registerHandler = (type, key, handler) => {
const handlers = msgHandlersMap[type] || {};
handlers[key] = handler;
msgHandlersMap[type] = handlers;
};