Friday 28 April 2017

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!



via Russell C.

No comments:

Post a Comment