Ivo Wetzel的答案似乎在0.9 Socket.io 中不再有效。
简而言之,您现在必须保存 并用于向其发送消息。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