简体   繁体   中英

Socket.io not sending to one socket in a room

I'm using socket.io to handle some of the server-client communication and matchmaking for a simple multiplayer game.

(for now) im automatically joining 2 players together by adding them into a socket.io room. When a room has 2 players in it I emit a "startGame" event to the room using socket.to(ROOM).emit(EVENT, EVENT_MSG) after doing a check

server side nodeJS:

game_start_state = checkRooms(socket, freeRooms);
if (game_start_state){
        console.log("told room", game_start_state, "to start their game!")
        socket.to(game_start_state).emit("startGame", game_start_state);
      }

but so far only the first socket that gets connected to the room receives the "startGame" event message, I've looked around and havent seen anyone else with the same problem. Below is the code that is fired after the client emits an event saying it wants to join a room.

server side nodeJS:

function checkRooms(socket, roomArray) {
// auto-matchmaking logic

  if(!roomArray || !roomArray.length){
    //if there is no room with space create a new one
    const room = uuid();
    r_list.push(room);    // r_list is just an array used to keep track of opened rooms for displaying to the user through some html
    freeRooms.push(room); // freeRooms is an array with rooms with just 1 socket connected
    joinRoom(socket, room);
    return(null);

  } else {
    // if there is a room with a space, try to connect the client to it
    const room = freeRooms[0];
    console.log(socket.id, "wants to join", room);
    // connect client to rooms
    joinRoom(socket, room);
    // room is now full so start the game
    freeRooms.pop(room);
    return(room);
  }
}

because for now there is only auto matchmaking, there will only be 1 room in the freeRooms array so I'm not worries about this.

Does anyone know where I could be messing up? Can provide more code examples if necessary.

socket.to(room).emit(...)

sends to every member of the room EXCEPT the referenced socket. You can see that documented here .

If you want to send to everyone in the room, then use:

io.to(room).emit(...)

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