简体   繁体   中英

Socket timeout on long POST node.js

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?

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

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM