socket.io和node cluster问题
发布于 2个月前 作者 JamCode 398 次浏览 来自 问答

各位有用过node cluster开多个socket.io进程吗?? 我这里开了之后,测试前端一直掉线,据说是hand shake时候会随机分配到一个socket.io进程上去,我的版本是socket.io 1.3.3, node v0.12.0, 使用了sticky-session第三方库也没解决

下面是服务端样例代码

var cluster = require(‘cluster’); var io = require(‘socket.io’); //require(‘strong-cluster-socket.io-store’).setup(); //var ClusterStore = require(‘strong-cluster-socket.io-store’)(io); if (cluster.isMaster) { for (var i = 0; i < 2; ++i) { cluster.fork(); } cluster.on('exit’, function(worker, code, signal) { console.log(‘socket worker ' + worker.process.pid + ' died’); cluster.fork(); }); cluster.on('listening’, function(worker, address) { console.log(“A socket worker with pid#” + worker.process.pid + " is now listening to:" + address.port); });

}else{ var ios = io.listen(3000); console.log(“start listen socket”); ios.sockets.on('connection’, function(socket) { console.log('get socket:’+socket.id);

    socket.on('disconnect', function(msg){
        console.log(msg);
    });
});

}

客户端样例代码

var socketArr = new Array(); var connectCount; process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); connectCount = val; }); for(var i=0; i<connectCount;++i){ f2(); } function f2(){ var socket = require(‘socket.io-client’)('http://xxx.xxx.xxx.xxx:3000’, {’force new connection’: true});

    socket.on('connect', function(){
        console.log('get connect ' + socket.id);
        //console.log(err);
    });

    socket.on('connect_error', function(err){
        console.log('connect_error '+err);
    });

    socket.on('disconnect', function(){
        console.log('disconnect');
    });

    //console.log('client connect to server');

    socketArr[i] = socket;
}
10 回复

sticky-session是正解,是不是没用对啊

也可以用nginx反代理设置个ip_hash搞定,模块的话我使用的是sticky-socket-cluster

@dayuoba sticky正确的~~你的那个情况也是正常的。做个sticky就可以了撒。

@dayuoba 用了github上的样例,不行啊,老是重连,是不是上面版本有问题了

5楼正解, socket.io官网已经给出有效的例子了, nginx里面要加 ip_hash

pm2 + nginx 多进程 正解

pm2 + nginx 多进程 正解

pm2 + nginx session + socket 放 redis/mongodb 数据库中共享

回到顶部