adam
adam

Reputation: 1453

How do I close a socket with timeout of 2 seconds without data?

I am trying to invoke socket like this:

socket.end();

I want to achieve something like this after waiting for 2 seconds and not receiving data:

socket.on('data', function(data){}); 

How can I acheive this?

Upvotes: 3

Views: 441

Answers (1)

clyfe
clyfe

Reputation: 23770

function socketEnd(){ socket.end(); }
var timeout = setTimeout(socketEnd, 2000);
socket.on('data', function(data){
    # got data, delay the timeout
    clearTimeout(timeout);
    timeout = setTimeout(socketEnd, 2000);
});

Upvotes: 3

Related Questions