forked from mengyxu/noob-components
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.
62 lines
1.4 KiB
62 lines
1.4 KiB
let websocket: WebSocket; |
|
const msgHandlersMap = {}; |
|
let lastUrl; |
|
let closeFlag = false; |
|
const messageQueue: any[] = []; |
|
|
|
export const closeWebSocket = () => { |
|
closeFlag = false; |
|
websocket?.close(); |
|
}; |
|
|
|
export const sendSocketMsg = (msg) => { |
|
if (websocket && websocket.readyState === WebSocket.OPEN) { |
|
websocket.send(JSON.stringify(msg)); |
|
} else { |
|
messageQueue.push(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; |
|
// Send any queued messages |
|
while (messageQueue.length > 0) { |
|
const msg = messageQueue.shift(); |
|
websocket.send(JSON.stringify(msg)); |
|
} |
|
}; |
|
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; |
|
};
|
|
|