David Conway
David Conway

Reputation: 9

How to change rooms easily in socket.io?

How to move from one room to another using socket.io. In the way that the users leaves previous room and joins to the new one.

Upvotes: 0

Views: 684

Answers (1)

Tamas Szoke
Tamas Szoke

Reputation: 5542

From the documentation, you can use the join and leave methods, so there's no combined function for this, but you can make one yourself:

const moveRoom = (socket, from, to) => {
  socket.leave(from);
  socket.join(to);
}

Usage:

moveRoom(socket, 'oldRoom', 'newRoom');

Get all rooms the client is in:

let rooms = Object.keys(socket.rooms);

You may want to check out the Socket.IO Emit cheatsheet.

Upvotes: 1

Related Questions