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

315
Visualizações
Callback help - SocketIo room name not being relayed to server

I'm sending messages from my client using socketIo and would like to assign sockets to certain rooms. The room is being declared on the client side (based on url) but I can't get the roomName variable to pass to the server side code (which would be the first step in establishing the connection).

The [docs][1] show me how to 'emit' to a room once I have the room name but I'm new-ish to js and struggling with the callback component as a first step.

Client script

const socket = io();

const messages = document.getElementById('messages');
const form = document.getElementById('form');
const roomContainer = document.getElementById('room-container');
const input = document.getElementById('input');

socket.on('connection', (socket) => {
    socket.join('create', (roomName) => {
        socket.join(roomName);
        console.log("hello from the connection function on socketIo.js", roomName)
    });
});

form.addEventListener('submit', function (e) {
    console.log(roomName," logged from submit function in socketIo.js");
    e.preventDefault();
    if (input.value) {
        const alias = socket.id.slice(-5);
        socket.emit('chat message', alias + ": " + input.value);
        input.value = '';
    }
});

socket.on('chat message', function (msg) {
    const item = document.createElement('ul');
    item.textContent = msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
});

Server code

io.sockets.on('connection', (socket) => {
    socket.on('create', (roomName) => {
        socket.join(roomName);
        console.log("roomName function test");
    });

    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
        console.log("message to terminal from chat message");
    });
});

Right now, "message to terminal from chat message" prints with each message but "roomName function test" never prints. I'm somehow missing that entire function with how I've structured the code.

How do I get the client to pass the roomName to the server? [1]: https://socket.io/docs/v4/rooms/

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

0

I figured it out using this youtube video but code below for anyone who stumbles across this in the future.

Client side code running in script

const socket = io();

const messages = document.getElementById('messages');
const form = document.getElementById('form');
const roomContainer = document.getElementById('room-container');
const input = document.getElementById('input');


joinRoom = () => {
    socket.emit('join room', roomName);
}

joinRoom();

form.addEventListener('submit', (event) => {
    console.log(roomName, " logged from submit function in socketIo.js");
    event.preventDefault();
    if (input.value) {
        const alias = socket.id.slice(-5);
        socket.emit('chat message', alias + ": " + input.value);
        input.value = '';
    }
});

socket.on('chat message', (msg) => {
    const item = document.createElement('ul');
    item.textContent = msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
});

Server code running on app.js

io.on('connection', (socket) => {

    socket.on('join room', (data) => {
        socket.join(data);
        console.log(socket.id, " joined room ", data);

        socket.on('chat message', (msg) => {
            io.to(data).emit('chat message', msg);
            console.log("chat message function from server worked");
        })
    })

    socket.on("disconnect", () => {
        console.log("user ", socket.id, " disconnected from server")
    })
});
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