【问题标题】:Node.js + Socket.io: Client not receiving messageNode.js + Socket.io:客户端未收到消息
【发布时间】:2020-02-01 11:58:52
【问题描述】:

我正在两个客户之间构建一个非常基本的聊天系统。虽然服务器可以接收来自客户端的消息,但它不能将消息发送给客户端(服务器向客户端发送消息时不会触发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]);
    }
}

【问题讨论】:

  • 什么是receiverId?它从何而来?为什么你认为io.to(receiverId) 会到达正确的套接字?如果你想发回给发件人,你会做user.emit(...),因为在你的结构中user是发送这个消息的套接字。
  • 尝试使用 user.emit("receiveMessage", [msgContent, receiverId]);

标签: javascript jquery node.js socket.io


【解决方案1】:

我认为您应该更改一些代码: 客户端(我假设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,
        })
    })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2021-05-23
    • 2014-08-02
    • 2017-12-22
    • 1970-01-01
    • 2012-04-07
    相关资源
    最近更新 更多