如何修改Node.js WebSocket服务器代码,仅将消息发送至Admin页面客户端
Hey there! Great job getting your basic WebSocket broadcast server up and running. To target only your Admin page client instead of broadcasting to everyone, we'll need to identify and track client types (admin vs regular client) on the server. Here's a step-by-step solution:
Step 1: Update Clients to Send Identity on Connection
First, modify your admin.html and client.html to send a "type" identifier right after connecting. This tells the server which kind of client it's dealing with:
For admin.html:
const ws = new WebSocket('ws://localhost:6969'); // Send admin identity once connected ws.onopen = () => { ws.send(JSON.stringify({ type: 'admin' })); }; // Handle incoming messages (optional) ws.onmessage = (event) => { console.log('Admin received:', event.data); };
For client.html:
const ws = new WebSocket('ws://localhost:6969'); // Send regular client identity once connected ws.onopen = () => { ws.send(JSON.stringify({ type: 'client' })); }; // Handle incoming messages (optional) ws.onmessage = (event) => { console.log('Client received:', event.data); };
Step 2: Modify the Server to Track Client Types
Update your Node.js server to store each client's type, then add logic to send messages only to admin clients when needed. Here's the revised code:
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const port = 6969; const server = http.createServer(express); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(ws) { // Initialize client type (default to 'client' if not specified) ws.clientType = 'client'; ws.on('message', function incoming(data) { try { // Parse incoming message to check for identity registration const message = JSON.parse(data); // If it's an identity message, update the client type if (message.type) { ws.clientType = message.type; console.log(`New ${message.type} client connected`); return; // Exit early, don't broadcast identity messages } // --- Logic to send message ONLY to admin clients --- wss.clients.forEach(function each(client) { if (client.clientType === 'admin' && client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ from: 'client', content: message.content // Assuming your client sends a 'content' field })); } }); // Optional: Keep original broadcast logic if needed (remove if not) // wss.clients.forEach(function each(client) { // if (client !== ws && client.readyState === WebSocket.OPEN) { // client.send(data); // } // }); } catch (error) { // Handle non-JSON messages (if any) console.log('Received non-JSON message:', data.toString()); } }); // Optional: Log when a client disconnects ws.on('close', () => { console.log(`${ws.clientType} client disconnected`); }); }); server.listen(port, () => { console.log(`WebSocket server running on port ${port}`); });
Key Changes Explained
- Client Type Tracking: We add a
clientTypeproperty to each WebSocket connection object, defaulting to 'client'. When a client sends its identity, we update this property. - Targeted Messaging: Instead of looping through all clients and excluding the sender, we now filter clients by
clientType === 'admin'to send messages only to the Admin page. - Error Handling: We wrap JSON parsing in a try/catch to handle any non-JSON messages gracefully.
Bonus: Server-Side Admin Messaging
If you want to send messages from the server directly to the admin (e.g., server status updates), you can add a helper function like this:
function sendToAdmin(message) { wss.clients.forEach(client => { if (client.clientType === 'admin' && client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(message)); } }); } // Example: Send active client count to admin every 10 seconds setInterval(() => { sendToAdmin({ type: 'status', content: `Active clients: ${wss.clients.size}` }); }, 10000);
内容的提问来源于stack exchange,提问作者yassine attou

