I’m making a multiplayer game using Socket.IO. What I want is this: when a player A joins another player B’s lobby, A’s socket id should be sent to B. Here’s what I’ve done so far.
From the client-side, the player clicks on a join button, which emits a “join-lobby” event.
On the server-side, I check whether the lobby/room exists, if so, the player joins that lobby, and also leaves their own lobby. After this, using socket.to(lobby).emit(), the server emits a “get-opponent” event which is supposed to send the sender’s socket id to the other player. However, this event is also being emitted to the sender.
Client side code
socket.emit("join-lobby", joinInput.value, (callback) => {
if(callback == null) {
toast.error("Lobby does not exist")
} else {
setLobby(callback.lobbyId)
console.log(`Current lobby: ${callback.lobby}`)
}
})
const getOpponent = (id) => {
setOpponentId(id)
}
useEffect(() => {
// other
socket.on("get-opponent", getOpponent)
return () => {
// other
socket.off("get-opponent", getOpponent)
};
}, [])
Server side code:
io.on("connection", (socket) => {
console.log(`${socket.id} connected`)
// other
socket.on("join-lobby", (lobby, callback) => {
// check whether lobby exists
let socketMap = io.sockets.sockets
let playerSocket = socketMap.get(lobby)
if(playerSocket == undefined) callback(null);
else {
// lobby exists
socket.join(lobby) // join another's lobby
socket.leave(socket.id) // leave own lobby
// send own id to other player
socket.to(lobby).emit("get-opponent", socket.id) // sends to sender also
callback({lobby})
}
})
})