node.js超时timeout详解


如果在指定的时间内服务器没有做出响应(可能是网络间连接出现问题,也可能是因为服务器故障或网络防火墙阻止了客户端与服务器的连接),则响应超时,同时触发http.ServerResponse对象的timeout事件.

response.setTimeout(time,[callback]);

也可以不在setTimeout中指定回调函数,可以使用时间的监听的方式来指定回调函数.

如果没有指定超时的回调函数,那么出现超时了,将会自动关闭与http客户端连接的socket端口.如果指定了超时的回调函数,那么超时了,将会出现调用回调函数,而不会自动关闭与http客户端连接的socket端口.

var http=require("http");

var server=http.createServer(function(req,res){

    if(req.url!=="/favicon.ico"){

        //超时监听

        /*res.setTimeout(1000);

        res.on("timeout",function(){

            console.log("响应超时.");

        });*/

        //超时直接回调

        res.setTimeout(1000,function(){

           console.log("响应超时.");

        });

        setTimeout(function(){

            res.setHeader("Content-Type","text/html");

            res.write("<html><head><meta charset='utf-8' /></head>");

            res.write("你好");

            res.end();

        },2000);

    }

});

server.listen(1337,"localhost",function(){

    console.log("开始监听"+server.address().port+"......");

});

运行代码结果:

查看图片

删除超时的回调函数后:

查看图片

浅析node.js中close事件
在http.ServerResponse对象的end方法被调用之前,如果连接被中断,将触发http.ServerResponse对象的close事件.varhttp=require("http");varserver=http.createServer(function(req,res){if(

教你如何使用node.js制作代理服务器
下面代码实现的功能是这样的:首先创建一个HTTP服务器,当服务器接收到客户端的请求后,向"www.taobao.com"网站请求数据,当从该网站接受到的响应数据后,将

node.js操作mongoDB数据库示例分享
连接数据库varmongo=require("mongodb");varhost="localhost";varport=mongo.Connection.DEFAULT_PORT;varserver=newmongo.Server(host,port,{auto_reconnect:true});//创建数据库所在的服务器服