在Node.js中,处理连接超时通常涉及到两个方面:服务器端和客户端。这里我们将分别讨论这两个方面的处理方法。
在服务器端,你可以使用server.setTimeout()
方法设置服务器的超时时间。如果在指定的时间内没有收到客户端的任何数据,服务器将关闭连接并触发一个'timeout'
事件。你可以监听这个事件并采取适当的措施,例如记录日志或关闭连接。
以下是一个简单的示例:
const http = require('http');
const server = http.createServer((req, res) => {
// 设置超时时间为5秒
server.setTimeout(5000, () => {
console.log('连接超时');
res.statusCode = 408;
res.end('请求超时');
});
// 处理请求
// ...
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
在客户端,你可以使用setTimeout()
方法设置请求的超时时间。如果在指定的时间内没有收到服务器的响应,你将收到一个'timeout'
错误。你可以监听这个错误并采取适当的措施,例如记录日志或重试请求。
以下是一个使用http
模块的客户端示例:
const http = require('http');
const options = {
hostname: 'localhost',
port: 3000,
path: '/',
method: 'GET',
timeout: 5000, // 设置超时时间为5秒
};
const req = http.request(options, (res) => {
// 处理响应
// ...
});
req.on('timeout', () => {
console.log('请求超时');
req.abort(); // 终止请求
});
req.on('error', (e) => {
console.error(`请求遇到问题: ${e.message}`);
});
req.end();
如果你使用的是其他HTTP客户端库(如axios
、request
等),它们通常也提供了设置超时的选项。你需要查阅相应库的文档以了解如何设置超时。