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.
|
|
import express from "express"; import { Server } from "ws"; import http from "http"; import bodyParser from "body-parser";
import cmdRouter from "./routes/cmd"; import debugRouter from "./routes/debug";
import { defaultStatus, StatusDatagram } from "./types/wsTypes"; import { wsSend } from "./utils/wss";
const app = express(); app.use(express.static("public")); 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());
// }
// });
// });
// 当连接关闭时触发
ws.send(JSON.stringify(getCurrStatus())); ws.on("close", () => { console.log("Client disconnected"); }); }); function getCurrStatus() { return app.locals["status"] as StatusDatagram["data"]; } app.locals["wss"] = wss; app.locals["status"] = defaultStatus;
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
app.use("/api/debug", debugRouter); app.use("/api/cmd", cmdRouter);
//@ts-ignore
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send("Something broke!"); });
// 监听端口
const PORT = process.env.PORT || 3003; server.listen(PORT, () => { console.log(`Server is listening on port ${PORT}`); });
|