javascript node.js 中的 socket.setTimeout()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16999373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:43:41  来源:igfitidea点击:

socket.setTimeout() in node.js

javascriptnode.jssocketshttpkeep-alive

提问by dima_mak

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.setTimeoutto close the socket after 2 sec timeout.
Here Is my code:

我试图实现基于 net 模块的 http 服务器。
我需要在其中实现保持活动状态,因此我调用sock.setKeepAlive(true)然后sock.setTimeout在 2 秒超时后关闭套接字。
这是我的代码:

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.htmlfor the first time it works fine, but if I make a refresh after 2 sec it throws an exception -

但是当我http://localhost:1234/profile.html第一次打开浏览器时它工作正常,但是如果我在 2 秒后刷新它会引发异常 -

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

错误:此套接字已被对方在 Socket.writeAfterFIN [as write] 处结束 (net.js:274:12)

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

如果我评论超时一切正常。
我的代码有什么问题?

采纳答案by dima_mak

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

解决方法是sock.destroy()在超时函数里面添加sock.end()