การกระจายข้อความไปยังไคลเอนต์
เรียนรู้วิธีส่งข้อความจากเซิร์ฟเวอร์ไปยังไคลเอนต์ที่เชื่อมต่ออยู่ทั้งหมด หรือส่งไปยังไคลเอนต์บางรายการ
การกระจายข้อความไปยังไคลเอนต์ เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Realtime Systems Programming และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Broadcasting?
Realtime applications often need to send updates to many users at once. Imagine a live sports score or a chat room.
Broadcasting is when your server sends a single message that is delivered to all currently connected clients.
Why Broadcast Messages?
Broadcasting is a fundamental pattern for many interactive applications:
- Live Updates: Stock prices, news alerts, sensor data.
- Chat Rooms: New messages visible to all participants.
- Notifications: System-wide alerts to all active users.
- Multiplayer Games: Player movements, game state changes for all players.
Server's Client List
To broadcast, your WebSocket server needs to know who's connected. The ws library (our Node.js WebSocket server library) automatically keeps track of all active connections.
When a client connects, its WebSocket object is added to an internal list. When it disconnects, it's removed.
Accessing Connected Clients
The ws library exposes the wss.clients property. This is a JavaScript Set containing all currently connected WebSocket client objects.
We can iterate over this Set to send messages to each individual client.
Implementing Full Broadcast
Here's how to modify your server to broadcast any message it receives to all connected clients:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log('Client connected');
ws.on('message', message => {
// Convert Buffer to string for display/processing
const msg = message.toString();
console.log(`Received: ${msg}`);
// Broadcast the received message to all connected clients
wss.clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`Broadcast: ${msg}`);
}
});
// Also send back to the sender as confirmation
if (ws.readyState === WebSocket.OPEN) {
ws.send(`You sent: ${msg}`);
}
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.send('Welcome to the broadcast server!');
});
console.log('WebSocket server started on port 8080');Broadcast Code Walkthrough
Let's break down the broadcast logic:
wss.clients.forEach(client => { ... }): This loop goes through every client in the connected set.if (client !== ws && client.readyState === WebSocket.OPEN): We check if the client is not the sender (to avoid echoing back to them twice) and if their connection is still open.client.send(`Broadcast: ${msg}`);: This is the magic! It sends the message to that specific client.
Testing the Broadcast
To test this, start your Node.js server. Then, open multiple browser tabs or client applications, all connecting to ws://localhost:8080.
When you send a message from one client, you should see it appear on all other connected clients!
Targeted Messaging
Broadcasting is powerful, but what if you need to send a message to just one or a few specific clients, not everyone?
This is called targeted messaging. Examples include private chat messages, direct user notifications, or status updates for specific admin users.
Identifying Specific Clients
The ws library doesn't inherently give clients unique IDs you can use for targeting. You'll need to implement this yourself:
- When a client connects, assign it a unique ID (e.g., a UUID).
- Store this ID along with the
wsobject in aMapor object on your server. - When a client sends a message that requires a targeted response, it can include its ID.
Simple Targeted Example
For a basic example, let's make a server that *only* sends a message back to the client that sent it (a direct echo). This demonstrates sending to a single ws object.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8081 }); // Use a different port
wss.on('connection', ws => {
console.log('Client connected for targeted example');
ws.on('message', message => {
const msg = message.toString();
console.log(`Received: ${msg}`);
// Send the message back ONLY to the client that sent it
if (ws.readyState === WebSocket.OPEN) {
ws.send(`You said: ${msg}`);
}
});
ws.on('close', () => {
console.log('Client disconnected from targeted example');
});
ws.send('Welcome! I will only talk directly to you.');
});
console.log('Targeted WebSocket server started on port 8081');Broadcasting Check
You're building a live chat application. When a user sends a message, you want *all* other users in the same chat room to see that message.
Recap & Next Steps
Fantastic work! You've mastered how to send messages from your Node.js WebSocket server:
- Broadcasting: Sending a message to all connected clients by looping through
wss.clients. - Targeted Messaging: Sending to a specific client using its individual
wsobject.
These techniques are crucial for building dynamic and interactive realtime applications. Next, we'll dive into how clients connect and interact with these server-side messages!
คำถามที่พบบ่อย
บทเรียน “การกระจายข้อความไปยังไคลเอนต์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การกระจายข้อความไปยังไคลเอนต์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การกระจายข้อความไปยังไคลเอนต์”
เรียนรู้วิธีส่งข้อความจากเซิร์ฟเวอร์ไปยังไคลเอนต์ที่เชื่อมต่ออยู่ทั้งหมด หรือส่งไปยังไคลเอนต์บางรายการ คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การกระจายข้อความไปยังไคลเอนต์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม
ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตั้งค่าโครงการ Node.js
- การใช้งานตรรกะฝั่งเซิร์ฟเวอร์
- การกระจายข้อความไปยังไคลเอนต์
- การจัดการห้องและช่องทาง