我正在使用插座。io和node.js,到目前为止,它似乎很好,但我不知道如何从服务器发送消息到特定的客户端,就像这样:

client.send(message, receiverSessionId)

但是.send()和.broadcast()方法似乎都不能满足我的需要。

我发现了一个可能的解决方案,是.broadcast()方法接受作为第二个参数的sessionid数组,不发送消息,所以我可以传递一个数组与所有的sessionid连接到服务器,除了一个我希望发送消息,但我觉得必须有一个更好的解决方案。

什么好主意吗?


当前回答

从1.4.5版本开始,请确保在io.to()中提供了一个正确前缀的socketId。 我把socketId客户端日志调试,它没有前缀,所以我最终永远搜索,直到我发现!所以如果Id没有前缀,你可能需要这样做:

io.to('/#' + socketId).emit('myevent', {foo: 'bar'});

其他回答

最简单、最优雅的方式

验证与插座工作。io v3.1.1

很简单:

client.emit("your message");

就是这样。好吧,但是它是如何工作的呢?

最小工作示例

下面是一个简单的客户机-服务器交互示例,其中每个客户机定期接收包含序列号的消息。每个客户端都有一个唯一的序列,这就是“我需要向特定的客户端发送消息”发挥作用的地方。

服务器

server.js

const
    {Server} = require("socket.io"),
    server = new Server(8000);

let
    sequenceNumberByClient = new Map();

// event fired every time a new client connects:
server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
    // initialize this client's sequence number
    sequenceNumberByClient.set(socket, 1);

    // when socket disconnects, remove it from the list:
    socket.on("disconnect", () => {
        sequenceNumberByClient.delete(socket);
        console.info(`Client gone [id=${socket.id}]`);
    });
});

// sends each client its current sequence number
setInterval(() => {
    for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
        client.emit("seq-num", sequenceNumber);
        sequenceNumberByClient.set(client, sequenceNumber + 1);
    }
}, 1000);

服务器开始在端口8000上监听传入的连接。一旦建立了新的连接,该客户端就被添加到跟踪其序列号的映射中。服务器还侦听断开连接事件,以便在客户端离开映射时将其从映射中删除。

每一秒,都会触发一个计时器。当它这样做时,服务器遍历映射,并向每个客户端发送带有当前序列号的消息,然后立即增加它。这就是它的全部。容易peasy。

客户端

客户端部分甚至更简单。它只是连接到服务器并侦听seq-num消息,并在每次消息到达时将其打印到控制台。

client.js

const
    io = require("socket.io-client"),
    ioClient = io.connect("http://localhost:8000");

ioClient.on("seq-num", (msg) => console.info(msg));

运行示例

安装所需的库:

npm install socket.io@3.1.1 socket.io-client@3.1.1

运行服务器:

node server

打开其他终端窗口,运行以下命令生成任意数量的客户端:

node client

我还准备了一个要点与完整的代码在这里。

Io.sockets.sockets [socket.id].emit(…)在v0.9中为我工作

套接字。IO允许您为套接字“命名空间”,这本质上意味着分配不同的端点或路径。

这可能会有帮助: http://socket.io/docs/rooms-and-namespaces/

每个套接字用套接字id作为名称连接一个房间,所以您可以

io.to('socket#id').emit('hey')

文档:http://socket.io/docs/rooms-and-namespaces/ # default-room

你可以使用

//只向sender-client发送消息

套接字。Emit ('message', 'check this');

//或者你可以发送给所有的监听器,包括发送者

io。Emit ('message', 'check this');

//发送给除发送方之外的所有侦听器

socket.broadcast。Emit ('message', 'this is a message');

//或者你可以把它送到一个房间

socket.broadcast.to(“聊天室”)。Emit ('message', '这是给所有人的消息');