node.js - 如何在 node.js http 模块超时时发送响应

标签 node.js http sockets timeout

在 nodejs.org 上 socket.setTimeout , 它说

When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.

但是当我这样测试代码时:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);

超时后立即关闭socket,没有数据回复给浏览器。这与文档完全不同。这是一个错误还是在 http 模块下处理套接字有什么技巧?

最佳答案

文档确实是正确的,但是看起来 http 模块添加了一个调用 socket.destroy() 的“超时”监听器。因此,您需要做的是通过调用 request.socket.removeAllListeners('timeout') 摆脱该监听器。 所以你的代码应该是这样的:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.removeAllListeners('timeout'); 
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);

关于node.js - 如何在 node.js http 模块超时时发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121760/

相关文章:

node.js - 你将如何在 Meteor 中进行繁重的处理?

android - URL中不同字段的含义

java - 可以从 Java Servlet API 发送到相对路径的重定向吗?

node.js - 与应用程序一起分发 Google API 凭据是否安全?

c++ - 套接字 RECV 陷入循环

sockets - FreeBSD jail 和套接字

node.js - 如何在node js中将url中的内容下载到文件中

node.js - 发送 header 后,Express Finalhandler 无法返回 404

mysql - NodeJS - 处理 100 多个并发连接的内存不足

java - Java:使用端口作为参数启动套接字服务器类