使用socket.io的Node.js集群

时间:2018-07-06 13:47:26

标签: node.js express redis socket.io

Nodejs对我来说处理异步非常奇怪。我大量使用了https://github.com/elad/node-cluster-socket.io中的结构。我最大的问题是缺乏处理群集的示例和文档。

代码:

var config = require(__dirname+'/Config/config.json');
var sql = require(__dirname+'/Server/mysql.js');
var express = require('express'),
    cluster = require('cluster'),
    net = require('net'),
    sio = require('socket.io'),
    sio_redis = require('socket.io-redis'),
    farmhash = require('farmhash');
var fs = require('fs');
var https = require('https');
var options = {
  key: fs.readFileSync(__dirname+'/Config/key.pem'),
  cert: fs.readFileSync(__dirname+'/Config/server.crt')
};

var app = express();


var num_processes = require('os').cpus().length;

if (cluster.isMaster) {
    console.log('master online');
    // This stores our workers. We need to keep them to be able to reference
    // them based on source IP address. It's also useful for auto-restart,
    // for example.
    var workers = [];

    // Helper function for spawning worker at index 'i'.
    var spawn = function(i) {
        workers[i] = cluster.fork();

        // Optional: Restart worker on exit
        workers[i].on('exit', function(code, signal) {
            console.log('respawning worker', i);
            spawn(i);
        });
    };

    // Spawn workers.
    for (var i = 0; i < num_processes; i++) {
        console.log('Worker Spawned');
        spawn(i);
    }

    // Helper function for getting a worker index based on IP address.
    // This is a hot path so it should be really fast. The way it works
    // is by converting the IP address to a number by removing non numeric
  // characters, then compressing it to the number of slots we have.
    //
    // Compared against "real" hashing (from the sticky-session code) and
    // "real" IP number conversion, this function is on par in terms of
    // worker index distribution only much faster.
    var worker_index = function(ip, len) {
        return farmhash.fingerprint32(ip) % len; // Farmhash is the fastest and works with IPv6, too
    };

    app.get('/',function(req, res) {
        res.sendFile(__dirname + '/client/index.html'); 
    });

    app.use('/client',express.static(__dirname + '/client'));

    // Create the outside facing server listening on our port.
    //var serv = https.createServer(options, app);
    var server = https.createServer(options, app);

    //var server = net.createServer({ pauseOnConnect: true }, function(connection) {
        // We received a connection and need to pass it to the appropriate
        // worker. Get the worker for this connection's source IP and pass
        // it the connection.
        //var worker = workers[worker_index(connection.remoteAddress, num_processes)];
        //worker.send('sticky-session:connection', connection);
        //console.log('Socket Connection!'+worker_index(connection.remoteAddress, num_processes));
    server.listen(config.ServerPort);
    var io = require('socket.io')(server,{});
    io.sockets.on('connection', function(socket){
        console.log('Socket Connection');       
        socket.on('signIn',function(data){
            console.log('signin Attempt');
            sql.LoginCheck(data,function(res){
                if(res){
                    console.log('signin Success');
                    socket.emit('signInresponse',{success:true});
                    var worker =workers[1];
                    worker.send('sticky-session:connection', server);
                    console.log('Socket Connection passed');
                }else{
                    console.log('signin Fail');
                    socket.emit('signInresponse',{success:false});
                }
            });

        });

        // socket.on('disconnect',function(){
            // delete SOCKET_LIST[socket.id];
            // console.log('socket disconnected');
        // });
    });


} else {
    // Note we don't use a port here because the master listens on it for us.
    var app = new express();

    // Here you might use middleware, attach routes, etc.

    // Don't expose our internal server to the outside.
    var server = app.listen(0, 'localhost');
        io = sio(server);

    // Tell Socket.IO to use the redis adapter. By default, the redis
    // server is assumed to be on localhost:6379. You don't have to
    // specify them explicitly unless you want to change them.
    io.adapter(sio_redis({ host: 'localhost', port: 6379 }));

    // Here you might use Socket.IO middleware for authorization etc.

    // Listen to messages sent from the master. Ignore everything else.
    process.on('message', function(message, connection) {
        if (message !== 'sticky-session:connection') {
            return;
        }

        // Emulate a connection event on the server by emitting the
        // event with the connection the master sent us.
        console.log('Socket Connection received');
        server.emit('connection', connection);
        connection.resume();
    });
}

控制台

master online
Worker Spawned
Worker Spawned
Worker Spawned
Worker Spawned
Socket Connection
signin Attempt
Admin
true
signin Success
Socket Connection passed
Socket Connection received
_http_server.js:304
    socket.setTimeout(self.timeout);
           ^

TypeError: socket.setTimeout is not a function
    at Server.connectionListener (_http_server.js:304:12)
    at emitOne (events.js:77:13)
    at Server.emit (events.js:169:7)
    at process.<anonymous> (/home/name/app/test.js:128:10)
    at emitTwo (events.js:92:20)
    at process.emit (events.js:172:7)
    at handleMessage (internal/child_process.js:686:10)
    at internal/child_process.js:497:7
    at Server.<anonymous> (internal/child_process.js:57:9)
    at Server.g (events.js:260:16)
respawning worker 1

不知道该如何处理该错误。但是,只是随机提交,似乎工人的听众才是罪魁祸首。我希望有人可以帮助我。

0 个答案:

没有答案