Node.js http.ServerResponse.setTimeout() 方法
httpServerResponse.setTimeout是 HTTP 模块中的 ServerResponse 类的内置应用程序编程接口,用于将 Socket 的超时值设置为毫秒(毫秒) 。
句法:
const response.setTimeout(msecs[, callback])
参数:该方法将第一个参数作为套接字超时值,以毫秒为单位,第二个参数是一个可选的回调函数。
返回值:此方法只返回一个回调函数以供进一步操作。
示例 1:文件名-index.js
Javascript
// Node.js program to demonstrate the
// response.setTimeout() method
// Importing http module
var http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
var httpServer = http.createServer(
function(request, response) {
// Setting the socket time out value
// by using setTimeout method
response.setTimeout(6000,() => {
console.log("socket is destroyed due to timeout")
})
});
// Listening to http Server
httpServer.listen(PORT, () => {
console.log("Server is running at port 3000...");
});
Javascript
// Node.js program to demonstrate the
// response.setTimeout() Method
// Importing http module
var http = require('http');
// Request and response handler
const httpHandlers = (request, response) => {
// Setting the socket time out value
// by using setTimeout method
response.setTimeout(5000,() => {
console.log("socket is destroyed due to timeout")
})
}
// Creating http Server
var httpServer = http.createServer(
httpHandlers).listen(3000, () => {
console.log("Server is running at port 3000...");
});
使用以下命令运行index.js文件:
node index.js
输出:
Server is running at port 3000...
socket is destroyed due to timeout
现在打开浏览器并转到http://localhost:3000/ ,您将看到以下输出:
ERR_CONNECTION_REFUSED
示例 2:文件名-index.js
Javascript
// Node.js program to demonstrate the
// response.setTimeout() Method
// Importing http module
var http = require('http');
// Request and response handler
const httpHandlers = (request, response) => {
// Setting the socket time out value
// by using setTimeout method
response.setTimeout(5000,() => {
console.log("socket is destroyed due to timeout")
})
}
// Creating http Server
var httpServer = http.createServer(
httpHandlers).listen(3000, () => {
console.log("Server is running at port 3000...");
});
使用以下命令运行index.js文件:
node index.js
输出:
Server is running at port 3000...
socket is destroyed due to timeout
现在打开浏览器并转到http://localhost:3000/ ,您将看到以下输出:
ERR_CONNECTION_REFUSED
参考: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_settimeout_msecs_callback