I've been experimenting with sockets lately, and I've ran into a bug that I'm not sure why is happening.
I created an index page with a button titled createRoom, which attempts creates a lobby/room in which other users can connect.
//index.js
createBtn.addEventListener('click', () => {
socket.emit("create-room", socket.id)
})
socket.on("redirect-host", roomId=>{
console.log("I JUST CREATED: " + roomId);
window.location.replace("/master") //lobby
})
//server.js
io.on("connection", socket => {
console.log("a user connected");
socket.on("create-room", hostId => { //receives the id of the person creating lobby
let roomId = Math.round(Math.random() * (999999 - 100000) + 100000);
socket.join(roomId)//generates room and then sends emit back to redirect host
console.log("Socket " + hostId + " created room: " + roomId);
socket.to(hostId).emit('redirect-host', roomId);
})
})
In index, there is a button you can click to generate a room which emits a create-room to server, which then creates a room and emits the room number back and tells server.js to redirect to a lobby screen (/master).
However, nothing seems to happen upon button press. My main suspect is that "redirect-host" is being sent to the wrong place, but then again I am new to sockets so I can't be sure of it.
Thank you.
EDIT: Resolved! To anyone wondering, the parameter "socket" is the connected socket. According to the socketio documentation, .to sends the emit to everyone but itself
Instead used,
io.in(roomId).emit('redirect-host', roomId);
Socket stands for the connected socket itself. Looking at the documentation:
// to all clients in room1 except the sender
socket.to("room1").emit(/* ... */);
Instead, I believe you want the server to send something to ALL clients in the room. For that, use io.in
io.in(roomId).emit('redirect-host', roomId);