Broadcasting lets a server send messages to all connected clients at once. This helps keep everyone updated together.
0
0
Broadcasting to connected clients in Node.js
Introduction
You want to send a chat message to all users in a chat room.
You need to update all users when a live event changes, like a score update.
You want to notify all connected clients about a system alert or announcement.
You want to push real-time data like stock prices to all users simultaneously.
Syntax
Node.js
io.emit('eventName', data);io is the main server object managing connections.
emit sends the event and data to all connected clients.
Examples
Sends a 'message' event with text to all clients.
Node.js
io.emit('message', 'Hello everyone!');
Sends an 'update' event with an object containing a score to all clients.
Node.js
io.emit('update', { score: 42 });
Sample Program
This Node.js server uses Socket.IO to broadcast messages to all connected clients. When a client connects, it sends a welcome message to everyone. When a client disconnects, it notifies all clients too.
Node.js
import { createServer } from 'http'; import { Server } from 'socket.io'; const httpServer = createServer(); const io = new Server(httpServer, { cors: { origin: '*' } }); io.on('connection', (socket) => { console.log('A client connected:', socket.id); // Broadcast a welcome message to all clients when someone connects io.emit('broadcast', `User ${socket.id} joined the chat`); socket.on('disconnect', () => { io.emit('broadcast', `User ${socket.id} left the chat`); }); }); httpServer.listen(3000, () => { console.log('Server listening on port 3000'); });
OutputSuccess
Important Notes
Broadcasting sends messages to all connected clients, including the sender.
You can also broadcast to all except the sender using socket.broadcast.emit().
Make sure to handle CORS properly to allow clients to connect from different origins.
Summary
Broadcasting sends the same message to all connected clients at once.
Use io.emit to broadcast from the server.
This is useful for chat apps, live updates, and notifications.