Node.js + Socket.io:客户端未收到消息

时间:2019-10-03 07:42:12

标签: javascript jquery node.js socket.io

我正在建立两个客户之间非常基本的聊天系统。尽管服务器可以从客户端接收消息,但是它无法将消息发送到客户端(服务器将消息发送到客户端时,不会触发receiveMessage事件)。下面是我的代码客户端:

$("#send-msg").submit(function(e) {
    e.preventDefault(); 
    socket.emit("sendMsg", [$("#msg-text").val(), chattingWith]);
});

socket.on("receiveMessage", receiveMsg);

function receiveMsg(data) {
    console.log("received msg"); // NOT OUTPUTTED
}

下面是我的代码服务器端:

var socket = io.connect();
var io = socket(server, { pingTimeout: 63000 }); 
io.sockets.on("connection", userConnect); 

function userConnect(user) {
    user.on("sendMsg", sendMsg);

    function sendMsg(msgData) {
        var msgContent = msgData[0];
        var receiverId = msgData[1];
        console.log("received message from " + receiverId); // ACTIVATED
        io.to(receiverId).emit("receiveMessage", [msgContent, receiverId]);
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您应该更改一些代码: 客户端(我假设chattingWith是一个唯一的会议室或聊天ID):

$("#send-msg").submit(function(e) {
   e.preventDefault(); 
   socket.emit("send message", $("#msg-text").val(), chattingWith);
});

socket.on("send Message", receiveMsg);

function receiveMsg(data) {
  console.log(data); //An array should be an output
}

服务器端代码:

io.on('connection', function(socket){
 socket.on('send message', function(data, id){
        socket.join(id)
        io.sockets.in(id).emit('sendMessage', {
            data: data,
        })
    })
})