Ivo Wetzel's answer doesn't seem to be valid in Socket.io 0.9 anymore.(Ivo Wetzel的答案似乎不再适用于Socket.io 0.9。)
In short you must now save the socket.id
and use io.sockets.socket(savedSocketId).emit(...)
to send messages to it.(简而言之,您现在必须保存socket.id
并使用io.sockets.socket(savedSocketId).emit(...)
向其发送消息。)
This is how I got this working in clustered Node.js server:(这就是我在集群Node.js服务器中使用它的方法:)
First you need to set Redis store as the store so that messages can go cross processes:(首先,您需要将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);
});
});
});
I omitted the clustering code here, because it makes this more cluttered, but it's trivial to add.(我在这里省略了聚类代码,因为它使它更加混乱,但添加起来很简单。)
Just add everything to the worker code.(只需将所有内容添加到工作人员代) More docs here http://nodejs.org/api/cluster.html(更多文档http://nodejs.org/api/cluster.html) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…