2024-09-11 19:06:44 +08:00
|
|
|
import { createServer } from "node:http";
|
|
|
|
import next from "next";
|
|
|
|
import { Server } from "socket.io";
|
2024-09-26 18:21:32 +08:00
|
|
|
import { fork } from "node:child_process";
|
2024-09-11 19:06:44 +08:00
|
|
|
|
|
|
|
const dev = process.env.NODE_ENV !== "production";
|
|
|
|
const hostname = "0.0.0.0";
|
2024-09-25 20:15:42 +08:00
|
|
|
const port = 22110;
|
2024-09-11 19:06:44 +08:00
|
|
|
// when using middleware `hostname` and `port` must be provided below
|
|
|
|
const app = next({ dev, hostname, port });
|
|
|
|
const handler = app.getRequestHandler();
|
|
|
|
|
|
|
|
app.prepare().then(() => {
|
|
|
|
const httpServer = createServer(handler);
|
|
|
|
|
|
|
|
const io = new Server(httpServer);
|
2024-09-26 18:21:32 +08:00
|
|
|
const forked = fork("./scanner.js");
|
2024-09-11 19:06:44 +08:00
|
|
|
|
|
|
|
io.on("connection", (socket) => {
|
2024-09-26 18:21:32 +08:00
|
|
|
console.log("[server][WebSocket]已连接");
|
|
|
|
socket.emit("msg", "connected");
|
2024-09-11 19:06:44 +08:00
|
|
|
|
2024-09-26 18:21:32 +08:00
|
|
|
// io.emit("msg", "io.emit");
|
|
|
|
forked.send("start");
|
2024-09-11 19:06:44 +08:00
|
|
|
|
2024-09-26 18:21:32 +08:00
|
|
|
socket.on("disconnect", () => {
|
|
|
|
console.log("[server][WebSocket]已断开连接");
|
|
|
|
forked.send("stop");
|
|
|
|
});
|
|
|
|
});
|
2024-09-11 19:06:44 +08:00
|
|
|
|
|
|
|
// socket_global.emit("msg","socket_global")
|
|
|
|
|
|
|
|
httpServer
|
|
|
|
.once("error", (err) => {
|
|
|
|
console.error(err);
|
|
|
|
process.exit(1);
|
|
|
|
})
|
|
|
|
.listen(port, () => {
|
2024-09-26 18:21:32 +08:00
|
|
|
console.log(`[server][服务器]已启用于 http://${hostname}:${port}`);
|
2024-09-11 19:06:44 +08:00
|
|
|
});
|
|
|
|
|
2024-09-26 18:21:32 +08:00
|
|
|
forked.on("message", (msg) => {
|
|
|
|
console.log("[server][子进程]]收到数据", msg);
|
|
|
|
io.emit("msg", msg);
|
|
|
|
});
|
2024-09-11 19:06:44 +08:00
|
|
|
|
2024-09-26 18:21:32 +08:00
|
|
|
//
|
|
|
|
});
|