Skip to content

Instantly share code, notes, and snippets.

@Nyaasu66
Last active July 18, 2024 07:09
Show Gist options
  • Save Nyaasu66/c529feae3b6c087403bf715e906e40f5 to your computer and use it in GitHub Desktop.
Save Nyaasu66/c529feae3b6c087403bf715e906e40f5 to your computer and use it in GitHub Desktop.
nodejs + websocket 测试服务端(需要 npm i ws)
const WebSocket = require("ws");
const os = require("os");
const readline = require("readline");
// 获取局域网地址
function getLocalIPAddress() {
const interfaces = os.networkInterfaces();
for (let iface of Object.values(interfaces)) {
for (let alias of iface) {
if (alias.family === "IPv4" && !alias.internal) {
return alias.address;
}
}
}
return "127.0.0.1";
}
const localIPAddress = getLocalIPAddress();
const port = 8080;
const server = new WebSocket.Server({ host: localIPAddress, port: port });
let clients = [];
server.on("connection", (ws) => {
clients.push(ws);
console.log("New client connected");
ws.on("message", (message) => {
try {
const data = JSON.parse(message);
console.log(
new Date().toLocaleTimeString(),
"Received:",
JSON.stringify(data)
);
} catch (e) {
console.error("Error parsing message:", e);
}
});
ws.on("close", () => {
clients = clients.filter((client) => client !== ws);
console.log("Client disconnected");
});
});
// 每秒发送测试消息
setInterval(() => {
const data = {
content: {
text: 'test';
}
time: new Date().valueOf(),
};
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
}, 1000);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on("line", (input) => {
if (input.trim().toLowerCase() === "r") {
clients.forEach((client) => client.close());
console.log("Closed all connections");
}
});
console.log(`WebSocket server is running on ws://${localIPAddress}:${port}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment