Browse Source

封装websocket: WsProxy

master
zhangjiming 4 months ago
parent
commit
a3855d92ac
  1. 30
      src/index.ts
  2. 4
      src/routes/cmd.ts
  3. 4
      src/routes/debug.ts
  4. 53
      src/utils/wss.ts

30
src/index.ts

@ -7,7 +7,7 @@ import cmdRouter from "./routes/cmd";
import debugRouter from "./routes/debug"; import debugRouter from "./routes/debug";
import { defaultStatus, StatusDatagram } from "./types/wsTypes"; import { defaultStatus, StatusDatagram } from "./types/wsTypes";
import { wsSend } from "./utils/wss";
import { WsProxy } from "./utils/wss";
const app = express(); const app = express();
app.use(express.static("public")); app.use(express.static("public"));
@ -15,31 +15,17 @@ app.use(bodyParser.urlencoded());
app.use(bodyParser.json()); app.use(bodyParser.json());
const server = http.createServer(app); 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.send(JSON.stringify(getCurrStatus()));
ws.on("close", () => {
console.log("Client disconnected");
});
});
})
// 在HTTP服务器上初始化WebSocket服务器
WsProxy.init(server);
function getCurrStatus() { function getCurrStatus() {
return app.locals["status"] as StatusDatagram["data"]; return app.locals["status"] as StatusDatagram["data"];
} }
app.locals["wss"] = wss;
app.locals["status"] = defaultStatus; app.locals["status"] = defaultStatus;
// app.get("/", (req, res) => { // app.get("/", (req, res) => {

4
src/routes/cmd.ts

@ -1,12 +1,12 @@
import express from "express"; import express from "express";
import { delay } from "../utils/helper"; import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
import { WsProxy } from "../utils/wss";
const router = express.Router(); const router = express.Router();
router.post("/", async (req, res) => { router.post("/", async (req, res) => {
await delay(200); await delay(200);
setTimeout(() => { setTimeout(() => {
wsSend(req.app.locals["wss"], {
WsProxy.send({
type: "cmd", type: "cmd",
data: { data: {
commandId: req.body.commandId, commandId: req.body.commandId,

4
src/routes/debug.ts

@ -1,7 +1,7 @@
import express from "express"; import express from "express";
import { delay } from "../utils/helper"; import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
import { StatusDatagram } from "../types/wsTypes"; import { StatusDatagram } from "../types/wsTypes";
import { WsProxy } from "../utils/wss";
const router = express.Router(); const router = express.Router();
router.post("/railArm", async (req, res) => { router.post("/railArm", async (req, res) => {
@ -11,7 +11,7 @@ router.post("/railArm", async (req, res) => {
curr.railArm.x = req.body.x; curr.railArm.x = req.body.x;
curr.railArm.y = req.body.y; curr.railArm.y = req.body.y;
curr.railArm.z = req.body.z; curr.railArm.z = req.body.z;
wsSend(req.app.locals["wss"], {
WsProxy.send({
type: "status", type: "status",
data: curr, data: curr,
}); });

53
src/utils/wss.ts

@ -1,11 +1,50 @@
import { Server } from "ws";
import { Datagram } from "../types/wsTypes";
import http from 'http';
import { Server, WebSocket } 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));
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));
} }
}); });
}
}
} }
Loading…
Cancel
Save