If the server does not respond within the specified time (maybe there is a problem with the network connection, or it may be because the server is malfunctioning or the network firewall blocks the client from the connection between the server), the response timeout and the timeout event of the http.ServerResponse object is triggered.
response.setTimeout(time,[callback]);
You can also not specify the callback function in setTimeout, you can use the time monitoring method to specify the callback function.
If there is no timeout callback function specified, then if the timeout occurs, the socket port connected to the http client will be automatically closed. If the timeout callback function specified, then the callback function will be called, and the socket port connected to the http client will be automatically closed.
The code copy is as follows:
var http=require("http");
var server=http.createServer(function(req,res){
if(req.url!=="/favicon.ico"){
//Timeout monitoring
/*res.setTimeout(1000);
res.on("timeout",function(){
console.log("Response timeout.");
});*/
//Timeout callback
res.setTimeout(1000,function(){
console.log("Response timeout.");
});
setTimeout(function(){
res.setHeader("Content-Type","text/html");
res.write("<html><head><meta charset='utf-8' /></head>");
res.write("Hello");
res.end();
},2000);
}
});
server.listen(1337,"localhost",function(){
console.log("Start listening"+server.address().port+"...");
});
Run code results:
After deleting the timeout callback function: