File size: 811 Bytes
e1bf766
 
 
 
 
 
 
f5cd24b
e1bf766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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}`);
});