| 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; |
|
|
| |
| app.get("/", (req, res) => { |
| res.sendFile(path.join(__dirname, "public", "index.html")); |
| }); |
|
|
| |
| 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 服务器!"); |
| }); |
|
|
| |
| server.listen(port, "0.0.0.0", () => { |
| console.log(`服务器运行在: http://localhost:${port}`); |
| }); |
|
|