Pregunta

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?

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top