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

client.send(message, receiverSessionId)

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

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

什么好主意吗?


当前回答

你也可以保留客户的参考资料。但这会让你的记忆很忙。

创建一个空对象并将客户端设置在其中。

const myClientList = {};

  server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
     myClientList[socket.id] = socket;   
  });
  socket.on("disconnect", (socket) => {
    delete myClientList[socket.id];
  });

然后通过对象中的id调用特定的客户端

myClientList[specificId].emit("blabla","somedata");

其他回答

每个套接字用套接字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

好吧,你必须抓住客户(惊喜),你可以选择简单的方法:

var io = io.listen(server);
io.clients[sessionID].send()

它可能会坏,我怀疑,但总是有可能io。客户端可能会被更改,因此请谨慎使用上述方法

或者您自己跟踪客户端,因此您将它们添加到连接侦听器中自己的客户端对象中,并在断开连接侦听器中删除它们。

我将使用后者,因为根据应用程序的不同,您可能希望在客户机上有更多的状态,因此可以使用类似clients[id] = {conn: clientConnect, data:{…}}可能会起作用。

在1.0版本中,你应该使用:

io.sockets.connected[socketid].emit();

你可以这样做

在服务器上。

global.io=require("socket.io")(server);

io.on("connection",function(client){
    console.log("client is ",client.id);
    //This is handle by current connected client 
    client.emit('messages',{hello:'world'})
    //This is handle by every client
    io.sockets.emit("data",{data:"This is handle by every client"})
    app1.saveSession(client.id)

    client.on("disconnect",function(){
        app1.deleteSession(client.id)
        console.log("client disconnected",client.id);
    })

})

    //And this is handle by particular client 
    var socketId=req.query.id
    if(io.sockets.connected[socketId]!=null) {
        io.sockets.connected[socketId].emit('particular User', {data: "Event response by particular user "});
    }

在客户端,它很容易处理。

var socket=io.connect("http://localhost:8080/")
    socket.on("messages",function(data){
        console.log("message is ",data);
        //alert(data)
    })
    socket.on("data",function(data){
        console.log("data is ",data);
        //alert(data)
    })

    socket.on("particular User",function(data){
        console.log("data from server ",data);
        //alert(data)
    })