Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

326
Visualizações
Adapting my chat app to work with rooms in socket io

So I have this simple chat application, and I'm looking to adapt it so the users can use the 4 different rooms I created. I'll try to explain how it works first, and I need to be guided, what would be the steps I need to take in order to make it work?(considering I'm a beginner) I've tried a lot of things but it always came out really buggy.

Client side:

//Get the room name out of the URL and send it to the server
function getRoomName() {
        let roomName = window.location.toString();
        if(roomName.includes('#') === true){
            roomName = roomName.split("#");
            roomName.splice(0, 1);
            roomName = roomName.toString();
            // Join room
            socket.emit('joinRoom', roomName);
        }
    }

//Here I am changing the URL when clicking on a room button (I got one of these for each button)
proiectFinalRoom.addEventListener('click', () =>{
        window.location.href='#proiectFinal'; 
        roomNameEdit.innerHTML = "#PROIECT-FINAL";  
    })

 sendBtn.addEventListener('click', () =>{
        sendMessage();
    })

    //Here I am sending the message to the server
    function sendMessage(){
        if(messageInput.value === ""){
            return;
        } else {
                   //Calling the getRoomName function (when sending a message)
            getRoomName();

            const text = messageInput.value;
            socket.emit('message', text);
        displayMessage();
        }
    }

Server side:

io.on('connection', (socket) => {
    socket.on('joinRoom', function(roomName){
        //Join room
        socket.join(roomName);

        //Send messages
        socket.on('message', (message) => {
            socket.broadcast.to(roomName).emit('message', `${message}`);          
        });
    });
});

This is the stage I am at right now, and It is definetely not working as it should. I already read a lot of articles about socket.io and rooms, but since english is not my first language I find it hard to understand where the problem is in my code.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think your Server side "message" call might be too nested. I would do something like this (keeping in mind that sockets maintains a collection of rooms):

io.on('connection', (socket) => {
    socket.on('joinRoom', function(roomName){
        //Join room
        socket.join(roomName);
    });

    //Send messages
    socket.on('message', (message) => {
        var room = getRoom(socket);
        socket.to(room).emit('message', `${message}`);          
    });
});

function getRoom(socket) {
  var room;
  for (let aRoom of socket.rooms) {
    if (aRoom !== socket.id) {
      room = aRoom;
    }
  }
  return room;
}

On the Client Side you use something like this. This way you only join the room once (I'm using React here):

  const [room, setRoom] = useState<string>();
  ...
  const socket = useContext(SocketContext);

  useEffect(() => {
    if (!room) {
      if (param) {
        var myRoom = param['room'];
        if (!myRoom) {
          socket.emit("ping");
        } else {
          socket.emit('join room', myRoom);
          setRoom(myRoom);
        }
      } else {
        socket.emit("ping");
      }
    }
  }, [room, param, socket]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda