Skip to content

Instantly share code, notes, and snippets.

@sandeep-cs-dev
Last active September 30, 2024 23:57
Show Gist options
  • Save sandeep-cs-dev/524bb74889df4e79e25828cca237d3b6 to your computer and use it in GitHub Desktop.
Save sandeep-cs-dev/524bb74889df4e79e25828cca237d3b6 to your computer and use it in GitHub Desktop.

Revisions

  1. sandeep-cs-dev revised this gist Sep 30, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion primary-round-robin-policy.js
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,7 @@ const workers = [];
    let workerIndex = 0;

    // Fork workers
    for (let i = 8; i <=numCPUs; i++) {
    for (let i = 1; i <=numCPUs; i++) {
    const worker = fork('worker-round-robin-policy.js'); // Fork the worker process
    workers.push(worker);
    }
  2. sandeep-cs-dev renamed this gist Sep 29, 2024. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. sandeep-cs-dev created this gist Sep 29, 2024.
    48 changes: 48 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    const { fork } = require('child_process');
    const net = require('net');
    const os = require('os');
    const numCPUs = os.cpus().length;
    const workers = [];
    let workerIndex = 0;

    // Fork workers
    for (let i = 8; i <=numCPUs; i++) {
    const worker = fork('worker-round-robin-policy.js'); // Fork the worker process
    workers.push(worker);
    }

    // Create the server in the primary process
    let server = net.createServer();
    let handle;

    // Start listening on the server
    server.listen({ port: 8080 });

    // Once the server starts listening, get the handle for the server
    server.once('listening', () => {
    handle = server._handle;
    console.log("Server listening on port 8080, server handle fd:", handle.fd);
    // Start accepting new connections
    acceptConnection();
    });

    // Function to handle new connections
    function acceptConnection() {
    // The server handle will receive new connections
    handle.onconnection = (err, clientHandle) => {
    if (err) {
    console.error("Error receiving new connection:", err);
    return;
    }
    console.log("New connection received, handle fd:", clientHandle.fd);
    // Distribute the connection to the workers
    distribute(clientHandle);
    };
    }

    // Function to distribute connections to workers
    function distribute(clientHandle) {
    workerIndex = (workerIndex + 1) % workers.length;
    const worker = workers[workerIndex];
    worker.send("new-conn", clientHandle); // Passing the handle properly to the worker
    }