test / index.js
wusama's picture
port 88 to 7860
f5cd24b verified
raw
history blame contribute delete
811 Bytes
const express = require("express");
const path = require("path");
const http = require("http");
const WebSocket = require("ws");
const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 7860;
// 1. 基础 HTTP 路由
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// 2. 初始化 WebSocket
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws) => {
console.log("有新客户端连接");
ws.on("message", (message) => {
console.log(`收到消息: ${message}`);
ws.send(`服务器回显: ${message}`);
});
ws.send("欢迎连接 WebSocket 服务器!");
});
// 3. 启动服务器
server.listen(port, "0.0.0.0", () => {
console.log(`服务器运行在: http://localhost:${port}`);
});