简而言之,你现在必须保存socket.id和使用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... 展开详请