石墨消解 mock
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.

61 lines
1.6 KiB

5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
  1. import express from "express";
  2. import { Server } from "ws";
  3. import http from "http";
  4. import bodyParser from "body-parser";
  5. import cmdRouter from "./routes/cmd";
  6. import debugRouter from "./routes/debug";
  7. import { defaultStatus, StatusDatagram } from "./types/wsTypes";
  8. import { wsSend } from "./utils/wss";
  9. const app = express();
  10. app.use(express.static("public"));
  11. app.use(bodyParser.urlencoded());
  12. app.use(bodyParser.json());
  13. const server = http.createServer(app);
  14. // 在HTTP服务器上初始化WebSocket服务器
  15. const wss = new Server({ server });
  16. wss.on("connection", ws => {
  17. console.log("Client connected");
  18. // ws.send("Welcome to the WebSocket server!");
  19. // ws.on("message", message => {
  20. // console.log(`Received message: ${message}`);
  21. // // 广播收到的消息给所有连接的客户端
  22. // wss.clients.forEach(client => {
  23. // if (client.readyState === ws.OPEN) {
  24. // client.send(message.toString());
  25. // }
  26. // });
  27. // });
  28. // 当连接关闭时触发
  29. ws.send(JSON.stringify(getCurrStatus()));
  30. ws.on("close", () => {
  31. console.log("Client disconnected");
  32. });
  33. });
  34. function getCurrStatus() {
  35. return app.locals["status"] as StatusDatagram["data"];
  36. }
  37. app.locals["wss"] = wss;
  38. app.locals["status"] = defaultStatus;
  39. // app.get("/", (req, res) => {
  40. // res.send("Hello World!");
  41. // });
  42. app.use("/api/debug", debugRouter);
  43. app.use("/api/cmd", cmdRouter);
  44. //@ts-ignore
  45. app.use((err, req, res, next) => {
  46. console.error(err.stack);
  47. res.status(500).send("Something broke!");
  48. });
  49. // 监听端口
  50. const PORT = process.env.PORT || 3003;
  51. server.listen(PORT, () => {
  52. console.log(`Server is listening on port ${PORT}`);
  53. });