Socket timeout on long POST node.js
Solution 1
From node's setTimeout documentation the connection will not be severed when a timeout occurs. That's why the browser's still waiting. You're still required to end() or destroy() the socket. You can increase the timeout by calling setTimeout on the socket.
socket.setTimeout(1000 * 60 * 300); // 5 hours
Solution 2
You can do a couple of things:
socket.setTimeout(/* number of milliseconds */);
If you do this, then the server can get a timeout event:
server.on('timeout', function(timedOutSocket) {
timedOutSocket.write('socket timed out!');
timedOutSocket.end();
});
Related videos on Youtube
kolombet
Updated on September 14, 2022Comments
-
kolombet over 1 year
Using node.js
http.createServer
to listen POST requests. If request completes fast, all works good. If request complete time > 5 seconds i get no response returned to client.Added event listeners on created sockets:
server.on('connection', function(socket) { log.info('SOCKET OPENED' + JSON.stringify(socket.address())); socket.on('end', function() { log.info('SOCKET END: other end of the socket sends a FIN packet'); }); socket.on('timeout', function() { log.info('SOCKET TIMEOUT'); }); socket.on('error', function(error) { log.info('SOCKET ERROR: ' + JSON.stringify(error)); }); socket.on('close', function(had_error) { log.info('SOCKET CLOSED. IT WAS ERROR: ' + had_error); }); });
Got those messages on middle of request (after about 10 sec after start):
info: SOCKET TIMEOUT info: SOCKET CLOSED. IT WAS ERROR: false
But on client socket do not get closed, so client wait for response. End of request completed with success, response sent (on closed socket!), but client still wait.
No idea how to block those timeouts. Removed all timeouts from code. Tried to add KeepAlive, no result.
socket.setKeepAlive(true);
How to prevent socket bultin timeout?
-
airato over 8 years1000 * 60 * 300 is not 5 minutes, it's 5 hours
-
airato over 8 yearsfirst param for .setTimeout is not number of seconds, it's milliseconds
-
tuxErrante about 5 yearsor for Request module
request.get(uri, {timeout: 1500},..
. github.com/request/request#timeouts