P
P
pik_os2015-07-31 13:32:40
Node.js
pik_os, 2015-07-31 13:32:40

How to set up a cluster on Node.js Express4 Socket.IO?

/bin/www:

#!/usr/bin/env node

/**
 * Module dependencies.
 */
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

var io               = require("socket.io")(server),
    passportSocketIo = require("passport.socketio"),
    express = require('express'),
    cookieParser = require('cookie-parser'),
    redis = require('redis'),
    session = require('express-session'),
    redisStore = require('connect-redis')(session);
var client = redis.createClient();

io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,
  key:         '***',       // the name of the cookie where express/connect stores its session_id
  secret:      '*********',    // the session_secret to parse the cookie
  store: new redisStore({ host: '*****', port: *******, client: client }),
  success:     onAuthorizeSuccess,  // *optional* callback on success - read more below
  fail:        onAuthorizeFail    // *optional* callback on fail/error - read more below
}));


var ioHandlers = require('../sockets')(io,passportSocketIo);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

When is the best time to spawn a child process?
Perhaps there are modules that will fit here better than the built-in cluster.
Google gives out many ways to enable the cluster, but they all somehow do not look like what I have.
If the child process is spawned in app.js, then the sockets will continue to run on the same thread.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2015-07-31
@MarcusAurelius

Threads in a node need to be spawned at the start of the application, this can be done using require('child_process').fork, but require('cluster').fork is just a wrapper around it, which allows you to pass sockets from the parent process to child processes to spray flow load. If you do not want to use cluster, then you will need to pass the socket handle to the child processes spawned via require('child_process').fork via IPC, and independently organize the spraying algorithm, for example, a simple Round Robin or a weighted Round Robin or sticking by IP. Why are you not satisfied with cluster? A year or two ago, it was unstable, I agree, I made patches for it myself, but now cluster works fine both in node.js and io.js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question