Search code examples
node.jstcpclient

Call a function everytime the client is idle


First time trying TCP and made a program which returns the square of the number sent by the client.

How to ask the client for a number everytime they are idle for 'n' seconds?

I tried the setTimeout method but it triggers after those 'n' seconds have passed and then it does does not get triggered again.

Client:

const net = require('net');
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

const options = {
    port : 1234
};

const client = net.createConnection(options, () => {
    console.log("Connected to server")
});

client.on('data', (data) => {
    console.log(data.toString());
});

client.setTimeout(2000, () => {
    readline.question('Number to be squared: ',(num) => {
        client.write(num);
    });
});

Server:

const net = require('net');
const port = 1234;

const server = net.createServer(conn => {
    console.log('New client joined');

    conn.on('data', (data) => {
        console.log(`Data received from client: ${data}`)
        data = parseInt(data);
        data = Math.pow(data,2);
        conn.write('From server- '+data.toString());
    });

    conn.on('end',() => {
        console.log('Connection stopped');
    });

    conn.on('error',(e) => {
        console.log('Connection stopped-', e.message);
    });
});

server.listen(port);

Solution

  • You need to listen to the timeout event, callback will be called only once. From the doc:

    The optional callback parameter will be added as a one-time listener for the 'timeout' event.

    socket.setTimeout(3000);//setting here.
    socket.on('timeout', () => {
      console.log('socket timeout');
      socket.end();
    });