0
0
Expressframework~5 mins

Broadcasting to rooms in Express

Choose your learning style9 modes available
Introduction
Broadcasting to rooms lets you send messages to a specific group of users connected to your server. It helps organize communication so only relevant people get the message.
You want to send chat messages only to users in the same chat room.
You need to update a group of users watching the same live event.
You want to notify players in the same game lobby about game status.
You want to send alerts to users subscribed to a particular topic.
You want to separate users by interest or location and send targeted updates.
Syntax
Express
io.to(roomName).emit(eventName, data);
Use io.to(roomName) to target a specific room.
emit sends the event and data to all clients in that room.
Examples
Sends 'Hello everyone!' message to all users in 'chatRoom1'.
Express
io.to('chatRoom1').emit('message', 'Hello everyone!');
Adds the current user to 'gameRoom' and sends a 'startGame' event with data to that room.
Express
socket.join('gameRoom');
io.to('gameRoom').emit('startGame', { level: 1 });
Removes user from 'oldRoom' and broadcasts 'New info' to 'newRoom'.
Express
socket.leave('oldRoom');
io.to('newRoom').emit('update', 'New info');
Sample Program
This Express server uses Socket.IO to let users join 'room1'. When a user sends a message, it broadcasts that message only to users in 'room1'.
Express
import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  // Join room 'room1'
  socket.join('room1');

  // Listen for messages from this socket
  socket.on('sendMessage', (msg) => {
    // Broadcast message to all in 'room1'
    io.to('room1').emit('receiveMessage', msg);
  });

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

httpServer.listen(3000, () => {
  console.log('Server listening on port 3000');
});
OutputSuccess
Important Notes
Rooms are just labels to group sockets; a socket can join multiple rooms.
Use socket.join(roomName) to add a user to a room.
Use io.to(roomName).emit(...) to send messages to all sockets in that room.
Summary
Broadcasting to rooms helps send messages to specific groups of users.
Use socket.join() to add users to rooms and io.to(room).emit() to send messages.
This keeps communication organized and efficient.