Categories
JavaScript Answers

How to create rooms in Node Socket.io?

Spread the love

To create rooms in Node Socket.io, we call in and join.

For instance, on client side, we write

const socket = io.connect();
socket.emit("create", "room1");

to call emit to emit the create event with the room name.

On server side, we write

io.sockets.on("connection", (socket) => {
  socket.on("create", (room) => {
    socket.join(room);
  });
});

to call on to listen for the create event and call join to create the room.

Then we can send messages to the room with

io.sockets.in(room).emit("event", data);

by call in with the room name.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.