【问题标题】:How to send to a client individually using socket_id?如何使用 socket_id 单独发送给客户端?
【发布时间】:2017-03-29 01:14:41
【问题描述】:

在客户端:

socket.on("event_test", function(msg){      console.log(msg); 
    alert(msg);
});

function test()
{
    socket.emit("hello","my_username");
}  

在服务器中:

socket.on("hello", function(new_username){
    socket.to(socket.id).emit("event_test", "pobe" );
    console.log(socket.id); // socket id is being printed correctly 
});

我编写此代码只是为了检查 .to() 功能。 正常的 socket.emit 工作正常。仅当我尝试将其发送给特定客户端时,它才不会发出并且我无法在客户端中接收它。 我究竟做错了什么 ? 跟着这个:https://socket.io/docs/emit-cheatsheet/

【问题讨论】:

    标签: javascript node.js websocket socket.io


    【解决方案1】:
    socket.on("hello", function(id, new_username){
        socket.broadcast.to(id).emit("event_test", "pobe" );
    });
    

    查看您的备忘单,您看起来是正确的,我不是专家,但我认为您可能一直在将您的消息从服务器发送到它自己。

    编辑:

    如果这不起作用,请尝试:

    socket.on("hello", function(new_username){
        socket.emit("event_test", "pobe" );
    });
    

    【讨论】:

    • 编辑后的工作正常。但是,如果我想将它发送到我应该使用的其他套接字。 \n 即假设我有 client1 、 client2 和 server 。当 client1 发出一些东西时,服务器应该向 client2 发送一条消息。这就是我想要实现的目标。
    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 2017-03-30
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多