Categories
JavaScript Answers

How to create rooms in socket.io?

Spread the love

Sometimes, we want to create rooms in socket.io.

In this article, we’ll look at how to create rooms in socket.io.

How to create rooms in socket.io?

To create rooms in socket.io, we can just listen for events and call socket.join to join the room.

For instance, we write

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

to call socket.emit with 'create' and 'room1' to emit the create event and room room1 from client side.

Then on server side, we write

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

to call sockets.on to listen to the connection event.

Then in the connection event handler, we call socket.on again to listen to the 'create' event that we get from client side.

In it, we call socket.join with the room, which should be set to 'room1' with socket.emit to join the 'room1'.

Conclusion

To create rooms in socket.io, we can just listen for events and call socket.join to join the room.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *