main.js:
var cluster = require( 'cluster' );
var os = require( 'os' );
if( cluster.isMaster ) {
cluster.on( 'exit', function( worker, code, signal ) {
console.log( 'worker #' + worker.id + ' died, and try restarting...' );
cluster.fork();
});
cluster.on( 'fork', function( worker ) {
console.log( 'worker #' + worker.id + ' is forking.' );
});
cluster.on( 'online', function( worker ) {
console.log( 'Yay, the worker responded after it was forked' );
});
cluster.on( 'listening', function( worker, address ) {
console.log( 'A worker with #'+ worker.id + ' is now connected to ' + address.address + ':' + address.port );
});
cluster.on( 'disconnect', function( worker ) {
console.log( 'The worker #' + worker.id + ' has disconnected' );
});
os.cpus().forEach(function() {
cluster.fork();
});
} else {
var server = require( 'server.js' );
var router = require( 'router.js' );
server.start( router.route );
}
process.on( 'SIGTERM', function() {
for( var id in cluster.workers ) {
process.kill( id );
}
process.exit( 0 );
});
process.on( 'message', function( msg ) {
console.log( 'process on message,and msg is : ' + msg );
});
server.js:
var net = require( 'net' );
var HOST = '127.0.0.1';
var PORT = 6969;
var Server = {};
var cluster = require( 'cluster' );
function start( route ) {
Server = net.createServer( function( socket ) {
//多进程监控接受
console.log('Worker #' + cluster.worker.id + ' has a request');
socket.on( 'data', function( data ) {
//下面是业务相关代码
route( socket, data );
});
socket.on( 'error', function( err ) {
if( err.code == 'EADDRINUSE' ) {
console.log( 'port ' + PORT + 'is using by other Server' );
}
});
socket.on( 'close', function( msg ) {
console.log( 'socket closed' );
});
});
Server.listen( PORT, HOST );
console.log( 'Server on.' );
}
exports.start = start;