网络编程 
首页 > 网络编程 > 浏览文章

浅析node.js中close事件

(编辑:jimmy 日期: 2025/12/28 浏览:3 次 )

在http.ServerResponse对象的end方法被调用之前,如果连接被中断,将触发http.ServerResponse对象的close事件.

复制代码 代码如下:
 var http=require("http");
 var server=http.createServer(function(req,res){
     if(req.url!=="/favicon.ico"){
         res.on("close",function(){
             console.log("连接中断")
         });
         setTimeout(function(){
             res.setHeader("Content-Type","text/html");
             res.write("<html><head><meta charset='utf-8' /></head>");
             res.write("你好");
             res.end();
         },10000);
     }
 });
 
 server.listen(1337,"localhost",function(){
     console.log("开始监听"+server.address().port+"......");
 });

上面代码是这样的:

当客户端发生请求后,经过10秒后向客户端发送"你好".同时监听close事件.

只要在10秒内关闭了服务器,服务端就会出现"连接被中断",因为10秒内,并不会执行res.end()方法.

上一篇:教你如何使用node.js制作代理服务器
下一篇:node.js超时timeout详解
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。