简体   繁体   中英

socket.io: assure socket joins only one room at a time

I'm working with socket.io 1.3.5. Clients can join rooms by sending a join<\/code> message. Serverside code:

socket.on('join', function(room) {
  socket.join(room);
});

If you're really just managing to one room at a time from your join message, then you could do this:

socket.on('join', function(room) {
    if (socket.lastRoom) {
        socket.leave(socket.lastRoom);
        socket.lastRoom = null;
    }
    socket.join(room);
    socket.lastRoom = room;
});

It just stores the last room that it was put in as a property on the socket.

This limits a given socket to only one room at a time as processed by your join message. If a client opens more than one socket, then each socket it opens can be in its own room since you haven't tracked this by an authenticated user id, only by socket. I don't understand your multiple instance/redis question since your requirement was that a given socket was only in one room at a time which this implements (a given socket only exists in one place).


If you wanted to change the requirements and limit one user to one room at a time and you were using multiple servers and the user could open multiple clients, then you'd have to get a lot more complicated, by storing the last room and server instance centrally in redis so you could enforce policy across multiple servers.

@SubscribeMessage('createRoom')
  @CacheTTL(2)
  async createRoom(
    @ConnectedSocket() client: Socket,
    @MessageBody() dto: webPrintFinger,
  ): Promise<DoorKey> {
    // get client rooms
    const rooms = Array.from(client.rooms);
    // this.logger.warn(rooms);
    if (rooms.length > 1) {
      //leave other room
      for (const doorId of rooms.slice(1)) {
        client.leave(doorId);
      }
    }
    client.join(newRoomId);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM