Thursday, 20 April 2017

Sending message using socket.io does not include name of sender

As the title suggests, the name of the sender is not included in the message that is send. Instead the message is displayed like this: [object Object] says: 'the message'. How can I display the name of the user instead of [object Object]. Below you can see the client-side-, and server-side code.

client-side:

// Sending the message (either by button click or enter) 
    $("#send").click(function(){
      var msg = $("#msg").val();
        if (msg.trim() == "") {
          return;
        } else {
            socket.emit("send message", msg);
            $("#msg").val("");
            $("#msg").focus();
        }
    });

    $("#msg").keypress(function(e){
      var msg = $("#msg").val();
      if (msg.trim() == "") {
          return;
        } else {
            if (e.which == 13) {
              socket.emit("send message", msg);
              $("#msg").val("");
              $("#msg").focus();
            }
          }
      });

server-side:

// When sending
client.on("send message", function(msg){
        client.to(client.room).emit("newMessageToOthers", people[client.id], msg);
    console.log("Message send",people[client.id], msg);
});



via JonasSH

No comments:

Post a Comment