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

200
Visualizações
Socket.IO emitting chat message to room

I currently have a system in socketio that creates rooms for individual messaging:

  socket.on("chat message", function(msg) {
    var roomname;
    if (msg.recipient > msg.sender) {
        roomname = msg.sender + "-" + msg.recipient;
    }
    else {
        roomname = msg.recipient + "-" + msg.sender;
    }
    if(!io.sockets.adapter.sids[users[msg.sender]][roomname]) {
        socket.join(roomname);
    }
    var clients = io.sockets.adapter.rooms[roomname].sockets;
    console.log(clients);
    io.in(roomname).emit("chat message", msg);
});

The if/else statement basically creates the roomname (person1-person2) in alphabetic order to prevent confusion when both parties join the room. The socket joins this room if it is not already in it. This is all triggered when the server receives "chat message". I have confirmed that the socket room joining part works. However, I seem to not be getting the message on the client end:

var socket = io();
socket.on("chat message", function(msg) {
    alert("received message");
    console.log(msg[message]);
    if (msg[message] != "") {
        $(".chat-history-div").append($("<li>").text(msg.message));
    }
});

I am not receiving the alert "received message" when I send a message. Why is this? Why am I not receiving a message from the server? Thanks!

EDIT: This is my client side emit("chat message):

 var socket = io();
 $("#form-send-message").submit(function () {
     var messageDetails = {
        sender: "<%=currentUser.username%>",
        recipient: $(this).find("textarea").val(),
        message: $(this).find(".chat-message-input").val()
    }
    socket.emit("chat message", messageDetails);
    $(".chat-message-input").val("");
    return false;
});
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

After analizing your code (OP provide full code via chat) I found the problem.

You have multiple socket.io connections in the client side, each var socket = io(); creates a new connection and a new socket id.

You were joining the room using this code:

var socket = io();
$("#form-send-message").submit(function () {
     var messageDetails = {
        sender: "<%=currentUser.username%>",
        recipient: $(this).find("textarea").val(),
        message: $(this).find(".chat-message-input").val()
    }
    socket.emit("chat message", messageDetails);
    $(".chat-message-input").val("");
    return false;
});

And then you expected the io.in(room).emit from the server to enter "chat message" listener, when you were overriding the socket and creating a new connection, the new socket never joined the room.

var socket = io(); //A new connection, a complete different socket

//This socket never joined the room

socket.on("chat message", function(msg) {
    alert("received message");
    console.log(msg.message);
    if (msg[message] != "") {
        $(".chat-history-div").append($("<li>").text(msg.message));
    }
});

You should only have 1 single connection.

So to fix your issue:

var socket = io();
$("#form-send-message").submit(function () {
     var messageDetails = {
        sender: "<%=currentUser.username%>",
        recipient: $(this).find("textarea").val(),
        message: $(this).find(".chat-message-input").val()
    }
    socket.emit("chat message", messageDetails);
    $(".chat-message-input").val("");
    return false;
});

socket.on("chat message", function(msg) {
    alert("received message");
    console.log(msg[message]);
    if (msg[message] != "") {
        $(".chat-history-div").append($("<li>").text(msg.message));
    }
});
over 4 years ago · Santiago Trujillo 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