forked from mengyxu/noob-components
Compare commits
1 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
309c06212d | 3 months ago |
11 changed files with 92 additions and 17 deletions
@ -1,5 +1,5 @@ |
|||||||
import { queryPage } from './base'; |
import { queryPage } from './base'; |
||||||
const root = 'log/action'; |
const root = 'log'; |
||||||
export const list = (example) => { |
export const list = (example) => { |
||||||
return queryPage(root, example); |
return queryPage(root, example); |
||||||
}; |
}; |
||||||
|
|||||||
@ -0,0 +1,52 @@ |
|||||||
|
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; |
||||||
|
}; |
||||||
Loading…
Reference in new issue