我试图实现基于网络模块的http服务器。
我需要在其中实现 keep-alive,所以我调用 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));
}
但是当我第一次打开浏览器并访问 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)
如果我评论超时一切正常。
我的代码有什么问题?
最佳答案
解决方案是在sock.end()
之后的超时函数中添加sock.destroy()
关于javascript - node.js 中的 socket.setTimeout(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16999373/