4

环境上下文

我们正在Heroku 上运行一个Node.js v0.10.25应用程序。Socket.io v0.9.16我们正在使用redis v2.6,更具体地说是 Heroku 附加组件“redis to go”,作为套接字存储。我们目前正在运行两个测功机。

问题

问题是套接字连接通过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>

对此的任何帮助将不胜感激,在此先感谢!

4

1 回答 1

0

如果通过“我们目前正在运行两个测功机”。你的意思是你有两个服务器实例,通过 redis pub/sub 进行通信,那么这应该是你想要的:http ://socket.io/docs/using-multiple-nodes/

于 2015-01-20T23:36:08.767 回答