socket.setTimeout() in node.js

12,880

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

Share:
12,880
dima_mak
Author by

dima_mak

Updated on June 04, 2022

Comments

  • dima_mak
    dima_mak almost 2 years

    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?