From 9fcd457c626d7c2a200f9b5d710a3e9e2128b756 Mon Sep 17 00:00:00 2001 From: hechang27-sprt Date: Tue, 30 Dec 2025 17:45:25 +0800 Subject: [PATCH] feat: add `websocket.ts` --- package.json | 4 ++++ plugs/index.ts | 1 + plugs/websocket.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 3 +++ 4 files changed, 60 insertions(+) create mode 100644 plugs/websocket.ts diff --git a/package.json b/package.json index b6f7456..61e29a4 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,10 @@ "types": "./dist/plugs/http/index.d.ts", "default": "./dist/plugs/http/index.js" }, + "./ws": { + "types": "./dist/plugs/websocket.d.ts", + "default": "./dist/plugs/websocket.js" + }, "./i18n": { "types": "./dist/plugs/i18n/index.d.ts", "default": "./dist/plugs/i18n/index.js" diff --git a/plugs/index.ts b/plugs/index.ts index 257495e..565478e 100644 --- a/plugs/index.ts +++ b/plugs/index.ts @@ -4,6 +4,7 @@ export * as Store from "./store"; export * as Http from "./http"; export * as Lang from "./i18n"; export * as Api from "./api"; +export * as WebSocket from "./websocket"; export * from "./constant"; export * from "./util/asyncUtil"; export * from "./util/objectUtil"; diff --git a/plugs/websocket.ts b/plugs/websocket.ts new file mode 100644 index 0000000..fb985f0 --- /dev/null +++ b/plugs/websocket.ts @@ -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; +}; diff --git a/tsconfig.json b/tsconfig.json index fdf99a2..d8ff62b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -42,6 +42,9 @@ "noob-mengyxu/http": [ "./plugs/http/index.ts" ], + "noob-mengyxu/ws": [ + "./plugs/websockets.ts" + ], "noob-mengyxu/i18n": [ "./plugs/i18n/index.ts" ],