Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda