From a3855d92ac6afbdf89599df25bf02e26dbb5afb3 Mon Sep 17 00:00:00 2001 From: zhangjiming Date: Tue, 25 Mar 2025 11:19:36 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=81=E8=A3=85websocket:=20WsProxy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.ts | 30 ++++++++------------------- src/routes/cmd.ts | 4 ++-- src/routes/debug.ts | 4 ++-- src/utils/wss.ts | 59 ++++++++++++++++++++++++++++++++++++++++++++--------- 4 files changed, 61 insertions(+), 36 deletions(-) diff --git a/src/index.ts b/src/index.ts index 17faed5..fc8ef48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import cmdRouter from "./routes/cmd"; import debugRouter from "./routes/debug"; import { defaultStatus, StatusDatagram } from "./types/wsTypes"; -import { wsSend } from "./utils/wss"; +import { WsProxy } from "./utils/wss"; const app = express(); app.use(express.static("public")); @@ -15,31 +15,17 @@ app.use(bodyParser.urlencoded()); app.use(bodyParser.json()); const server = http.createServer(app); -// 在HTTP服务器上初始化WebSocket服务器 -const wss = new Server({ server }); - -wss.on("connection", ws => { - console.log("Client connected"); - // ws.send("Welcome to the WebSocket server!"); - // ws.on("message", message => { - // console.log(`Received message: ${message}`); - // // 广播收到的消息给所有连接的客户端 - // wss.clients.forEach(client => { - // if (client.readyState === ws.OPEN) { - // client.send(message.toString()); - // } - // }); - // }); - // 当连接关闭时触发 + +WsProxy.addActionForClientConnect((ws) => { ws.send(JSON.stringify(getCurrStatus())); - ws.on("close", () => { - console.log("Client disconnected"); - }); -}); +}) +// 在HTTP服务器上初始化WebSocket服务器 +WsProxy.init(server); + function getCurrStatus() { return app.locals["status"] as StatusDatagram["data"]; } -app.locals["wss"] = wss; + app.locals["status"] = defaultStatus; // app.get("/", (req, res) => { diff --git a/src/routes/cmd.ts b/src/routes/cmd.ts index 6f6288f..f5b2422 100644 --- a/src/routes/cmd.ts +++ b/src/routes/cmd.ts @@ -1,12 +1,12 @@ import express from "express"; import { delay } from "../utils/helper"; -import { wsSend } from "../utils/wss"; +import { WsProxy } from "../utils/wss"; const router = express.Router(); router.post("/", async (req, res) => { await delay(200); setTimeout(() => { - wsSend(req.app.locals["wss"], { + WsProxy.send({ type: "cmd", data: { commandId: req.body.commandId, diff --git a/src/routes/debug.ts b/src/routes/debug.ts index 9f6e4a1..aad2cf6 100644 --- a/src/routes/debug.ts +++ b/src/routes/debug.ts @@ -1,7 +1,7 @@ import express from "express"; import { delay } from "../utils/helper"; -import { wsSend } from "../utils/wss"; import { StatusDatagram } from "../types/wsTypes"; +import { WsProxy } from "../utils/wss"; const router = express.Router(); router.post("/railArm", async (req, res) => { @@ -11,7 +11,7 @@ router.post("/railArm", async (req, res) => { curr.railArm.x = req.body.x; curr.railArm.y = req.body.y; curr.railArm.z = req.body.z; - wsSend(req.app.locals["wss"], { + WsProxy.send({ type: "status", data: curr, }); diff --git a/src/utils/wss.ts b/src/utils/wss.ts index 8181483..4c35d11 100644 --- a/src/utils/wss.ts +++ b/src/utils/wss.ts @@ -1,11 +1,50 @@ -import { Server } from "ws"; -import { Datagram } from "../types/wsTypes"; - -export function wsSend(wss: Server, data: Datagram) { - // 广播消息给所有连接的客户端 - wss.clients.forEach(client => { - if (client.readyState === client.OPEN) { - client.send(JSON.stringify(data)); - } - }); +import http from 'http'; +import { Server, WebSocket } from 'ws'; +import { Datagram } from '../types/wsTypes'; + +export class WsProxy { + public static server: Server; + + private static actionsWhenClientConnect: ((ws: WebSocket) => void)[] = []; + + static addActionForClientConnect(act: (ws: WebSocket) => void) { + this.actionsWhenClientConnect.push(act); + } + static init(server: http.Server) { + this.server = new Server({ server }); + this.onConnection(); + } + + private static onConnection() { + this.server.on('connection', ws => { + console.log('Client connected'); + // ws.send("Welcome to the WebSocket server!"); + // ws.on("message", message => { + // console.log(`Received message: ${message}`); + // wss.clients.forEach(client => { + // if (client.readyState === ws.OPEN) { + // client.send(message.toString()); + // } + // }); + // }); + this.actionsWhenClientConnect.forEach(act => act(ws)); + + ws.on('close', () => { + console.log('Client disconnected'); + }); + }); + } + + public static send(data: Datagram, ws?: WebSocket) { + // DeviceContext + if (ws) { + ws.send(JSON.stringify(data)); + } else { + this.server.clients.forEach(ws => { + if (ws.readyState === ws.OPEN) { + ws.send(JSON.stringify(data)); + } + }); + } + } }