Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I trying to implement http server based on net module.
I need to implement keep-alive in it, so I call to sock.setKeepAlive(true) and then sock.setTimeout to close the socket after 2 sec timeout.
Here Is my code:

var server = net.createServer({ allowHalfOpen: false},socketListener);

function start(port){
    server.listen(port,'localhost');
}

function socketListener(sock){
    sock.setEncoding("utf8");
    sock.setKeepAlive(true);
    sock.setTimeout(2000,function(){
        sock.end("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n");
    });
    sock.on("data",responser.responserCreator(sock,httpParser,baseDir,stat));
}

But when I open a browser and to http://localhost:1234/profile.html for the first time it works fine, but if I make a refresh after 2 sec it throws an exception -

Error: This socket has been ended by the other party at Socket.writeAfterFIN [as write] (net.js:274:12)

If I comment the timeout everthing works fine.
What wrong in my code?

share|improve this question
1  
Enabling TCP keepalive and setting an unrealistically read timeout doesn't constitute implementing HTTP keepalive. They are completely different things. HTTP keepalive requires keeping connections open and sending the appropriate headers to say so. –  EJP Jun 8 at 12:54
 
Tnx for answer.So I need to delete timeout on socket and only add Connection: Keep-Alive header + send Connection: close on timeout(2 sec - it is by spec. I received)? –  dima_mak Jun 9 at 15:18
 
Tryed to change the timeout to setTimeout(function(){ console.log("Connection closed"); // Send Connection: close on timeout sock.end("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"); },settings.LAST_REQUEST_TIMEOUT_SEC*1000); and removed sock.setKeepAlive(true);, but same problem –  dima_mak Jun 9 at 16:20

1 Answer

up vote 0 down vote accepted

The solution is to add sock.destroy() inside the timeout function right after sock.end()

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.