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

client.send(message, receiverSessionId)

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

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

什么好主意吗?


当前回答

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

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

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

其他回答

Ivo Wetzel的答案在Socket中似乎不成立。IO 0.9。

简而言之,现在必须保存套接字。使用io.sockets.socket(savedSocketId).emit(…)向它发送消息。

这是我如何在集群Node.js服务器中工作的:

首先,你需要设置Redis存储为存储,以便消息可以跨进程:

var express = require("express");
var redis = require("redis");
var sio = require("socket.io");

var client = redis.createClient()
var app = express.createServer();
var io = sio.listen(app);

io.set("store", new sio.RedisStore);


// In this example we have one master client socket 
// that receives messages from others.

io.sockets.on('connection', function(socket) {

  // Promote this socket as master
  socket.on("I'm the master", function() {

    // Save the socket id to Redis so that all processes can access it.
    client.set("mastersocket", socket.id, function(err) {
      if (err) throw err;
      console.log("Master socket is now" + socket.id);
    });
  });

  socket.on("message to master", function(msg) {

    // Fetch the socket id from Redis
    client.get("mastersocket", function(err, socketId) {
      if (err) throw err;
      io.sockets.socket(socketId).emit(msg);
    });
  });

});

我在这里省略了集群代码,因为这会使它更加混乱,但添加它很简单。只需将所有内容添加到工作代码中即可。更多文档请点击这里http://nodejs.org/api/cluster.html

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

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

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

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

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

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

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

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