Multiple socket connection for TCP server, How to scale using worker thread in Nodejs

967 Views Asked by At

I have following code, As there are N number of socket sending sequential stream. how to scale this using worker threads in nodejs.

const Net = require('net');
const port = 8080;
const server = new Net.Server();
const processor = require('processor.js');

server.listen(port, function() {
    console.log(`Server listening for connection requests on socket localhost:${port}`.);
});

server.on('connection', function(socket) {
    console.log('A new connection has been established.');
    
    let connectionInfo = {};
    connectionInfo.id = `${socket.remoteAddress}:${socket.remotePort}`;
    connectionInfo.partialBuffer= undefined;

    socket.on('data', function(chunk) {
        let chunkBuffer = Buffer.from(chunk);
        if(connectionInfo.partialBuffer){
            chunkBuffer = Buffer.concat([connInfo.partialBuffer, chunkBuffer]);
        }
        processor.processChunk(connectionInfo, chunkBuffer); // set connectionInfo.partialBuffer in processChunk() function 
    });

    socket.on('end', function() {
        console.log('Closing connection with the client');
    });

    socket.on('error', function(err) {
        console.log(`Error: ${err}`);
    });
});
0

There are 0 best solutions below