如果服务器在指定的时间内没有响应(可能是网络之间的连接出现问题、服务器故障或网络防火墙阻止了客户端和服务器之间的连接),响应将超时并触发http的超时事件。服务器响应对象。
response.setTimeout(time,[回调]);
您也可以通过监听时间来指定回调函数,而不是在setTimeout中指定回调函数。
如果没有指定超时回调函数,当超时发生时,连接到http客户端的套接字端口将自动关闭。如果指定了超时回调函数,当超时发生时将调用回调函数,但连接到http客户端的套接字端口不会自动关闭。
复制代码如下: var http=require(' http ');var server=http . CreateServer(function(req,res){ if(req.url!=='/favicon.ico'){ //超时监听/* RES . settimeout(1000);Res. on('超时',function () {console.log('响应超时'));});*///回调res.settimeout (1000,function () {console.log('响应超时'));});setTimeout(函数(){ res.setHeader('Content-Type ',' text/html ');RES . write(' htmlownerta charset=' utf-8 '//head ');RES . write(' hello ');RES . end();},2000);}});Server.listen (1337,' localhost ',function(){ console . log(' start listen ' server . address()。港口“.”);});
运行代码结果:
删除超时回调函数:后