Skip to content

Example of second way of delegating connections to cluster workers #9204

Closed
@basickarl

Description

@basickarl

https://nodejs.org/api/cluster.html#cluster_how_it_works states:

The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.

I've read the documentation but haven't really figured out how to put it together. I've come up with the following code (I don't know how to pass the socket object):

'use strict';

const cluster = require('cluster');
const net = require('net');
const http = require('http');

if (cluster.isMaster) {
    const numCPUs = require('os').cpus().length;
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    const socket = new net.Socket(); // Socket to send to the worker.
    socket.connect(3000);
} else {
    http.Server((req, res) => {
        res.writeHead(200);
        res.end('hello world\n');
    }).listen(socket);
}

Would be nice to see this in the documentation later^^.

Metadata

Metadata

Assignees

No one assigned

    Labels

    clusterIssues and PRs related to the cluster subsystem.questionIssues that look for answers.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions