JGC
JGC

Reputation: 12997

Force a connection to be closed after a period in nodejs

I have user http.request for making connection to another server in nodejs. Unfortunately that server has a delay in responding in some situations. So I want to close the request after some period. I have found following code but this close connection if target server was not reachable or connection has not been established.

req.on('socket', function (socket) {
    socket.setTimeout(myTimeout);  
    socket.on('timeout', function() {
        req.abort();
    });
});

What I want is closing connection after for example 2 seconds wether data is coming or not.

Does anyone has any idea?

Upvotes: 1

Views: 598

Answers (1)

smnbbrv
smnbbrv

Reputation: 24541

I don't really know the sockets library you use, maybe it has some ready and nice solution for that as well, but it looks simple to just use setTimeout function:

req.on('socket', function (socket) {
    setTimeout(function() {
        // maybe some additional condition here
        // or recursive call if you want to wait 2 more seconds
        // or whatever else
        // but if you want to just abort...
        req.abort();
    }, 2000);
});

Again, this maybe looks like a workaround, but it definitely should be enough as I understand from your request.

Upvotes: 1

Related Questions