|
|
@ -1,35 +1,48 @@ |
|
|
|
import express from "express"; |
|
|
|
import { Server } from "ws"; |
|
|
|
import http from 'http'; |
|
|
|
import http from "http"; |
|
|
|
import bodyParser from "body-parser"; |
|
|
|
|
|
|
|
const app = express(); |
|
|
|
app.use(express.static('public')); |
|
|
|
app.use(express.static("public")); |
|
|
|
app.use(bodyParser.urlencoded()); |
|
|
|
app.use(bodyParser.json()); |
|
|
|
|
|
|
|
app.get("/", (req, res) => { |
|
|
|
res.send("Hello World!"); |
|
|
|
}); |
|
|
|
app.post("/test", (req, res) => { |
|
|
|
(req.app.locals["wss"] as Server).clients.forEach(client => { |
|
|
|
if (client.readyState === 1) { |
|
|
|
client.send(JSON.stringify(req.body)); |
|
|
|
} |
|
|
|
}); |
|
|
|
res.json({ success: true, data: req.body }); |
|
|
|
}); |
|
|
|
|
|
|
|
const server = http.createServer(app); |
|
|
|
// 在HTTP服务器上初始化WebSocket服务器
|
|
|
|
const wss = new Server({server}); |
|
|
|
wss.on('connection',(ws) => { |
|
|
|
console.log('Client connected'); |
|
|
|
ws.send('Welcome to the WebSocket server!'); |
|
|
|
ws.on('message', (message) => { |
|
|
|
console.log(`Received message: ${message}`); |
|
|
|
const wss = new Server({ server }); |
|
|
|
|
|
|
|
wss.on("connection", ws => { |
|
|
|
console.log("Client connected"); |
|
|
|
ws.send("Welcome to the WebSocket server!"); |
|
|
|
ws.on("message", message => { |
|
|
|
console.log(`Received message: ${message}`); |
|
|
|
// 广播收到的消息给所有连接的客户端
|
|
|
|
wss.clients.forEach(client => { |
|
|
|
if (client.readyState === ws.OPEN) { |
|
|
|
client.send(message.toString()); |
|
|
|
} |
|
|
|
}); |
|
|
|
}) |
|
|
|
}); |
|
|
|
// 当连接关闭时触发
|
|
|
|
ws.on('close', () => { |
|
|
|
console.log('Client disconnected'); |
|
|
|
ws.on("close", () => { |
|
|
|
console.log("Client disconnected"); |
|
|
|
}); |
|
|
|
}) |
|
|
|
}); |
|
|
|
|
|
|
|
app.locals["wss"] = wss; |
|
|
|
|
|
|
|
// 监听端口
|
|
|
|
const PORT = process.env.PORT || 3003; |
|
|
|