我们正在Heroku上运行Node.js v0.10.25
个应用Socket.io v0.9.16
的应用。我们使用redis v2.6
,更具体地说是Heroku附加组件“redis to go”,作为套接字存储。我们目前有两个dynos在运行。
问题是通过xhr-polling
的套接字连接被发送到套接字但不总是在同一套接字上接收。一个例子:
服务器端代码
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3001);
var RedisStore = require('socket.io/lib/stores/redis')
var redis = require('redis')
var rtg = require("url").parse(FULL_REDIS_PATH);
var hostname = rtg.hostname;
var database = rtg.auth.split(":")[0];
var portRedis = rtg.port;
var password = rtg.auth.split(":")[1];
var pub = redis.createClient(portRedis, hostname)
var sub = redis.createClient(portRedis, hostname)
var client = redis.createClient(portRedis, hostname)
pub.auth(password, function (err) { if (err) throw err; });
sub.auth(password, function (err) { if (err) throw err; });
client.auth(password, function (err) { if (err) throw err; });
/** Initialize RedisStore for socket.io **/
io.set('store', new RedisStore({
redis : redis
, redisPub : pub
, redisSub : sub
, redisClient : client
}));
/** Configuration Settings for socket.io **/
io.set('log level', 1);
io.set('transports', ['flashsocket','xhr-polling']);
io.set('polling duration', 10);
io.sockets.on('connection', function (socket) {
/** Associate Client ID to Socket ID **/
client.set('client-'+client_id,socket.id, function(err){
if (err) throw err;
console.log("User " + client_id + " socket is now... " + socket.id);
/**
* Retrieve the Socket ID by the User's ID
* Send a socket.emit message based on the Socket ID retrieved from Redis.
**/
client.get('client-'+client_id,function(err, response){
socketId = response;
io.sockets.socket(socketId).emit('response',{user_id: client_id});
console.log('Retrieving User ' + client_id + ' - socket is now... ' + socket.id);
});
});
});
客户端代码
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3001');
socket.on('response', function (data) {
console.log(data);
});
</script>
非常感谢任何有关此事的帮助,提前谢谢!
答案 0 :(得分:0)
如果通过&#34;我们目前有两个dynos正在运行。&#34;你的意思是你有两个服务器实例,通过redis pub / sub进行通信,那么这应该是你所要求的:http://socket.io/docs/using-multiple-nodes/