如果HTTP客户端关闭连接Servlet怎么得到通知?

我指的是 *数据传输过程中* HTTP连接被客户端关闭。下面是我以前在tomcat-user@jak
arta.apache.org上的问题原文:

I notice that the following jsp is still running when the client terminates
his web browser:

<%
for(int i=0;i<100;i++){
try{
Thread.currentThread().sleep(2000);
System.out.println((i+1)+": Hello");
for(int j=0;j<1000;j++)
out.println("hello");

}
catch(Exception e){
System.out.println("Exception");
e.printStackTrace();
}
}
%>

So althougth the jsp/servlet can no more write any data to the
browser(which is terminated by the client),the jsp/servlet can still write
the the jsp output stream "out" without any exception thrown by the
"println" method,and the jsp/servlet is blind to the fact that it can no
more really write any thing to the client(the client can no more receive
the data),it keeps running util it finishes the "for" cycles,just as
nothing happens.

But I want to be notified when the HTTP connection is close by the web
client.How can I do that?

望各位大牛解答,感激不尽。

这个问题其实在很多地方问了好几遍,但是很多回复者常常误解我的意思,看来我的中
英文表达能力还要好好加强。现在我想把我的问题写得更清楚一些,以便各位大牛更容
易知道我想说什么。

是这样的,我想让Servlet来对用户提供HTTP方式的下载功能(当然,这个下载支持Rang
e),下载的数据量是巨大的(10-500M)。Servlet内部的逻辑大概是这样的:

doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException{

int ch;
InputStream in=null;
OutputStream out=null;

try{
in=new MyInputStream(...);
out=response.getOutputStream();
while((ch=in.read())!=-1){
out.write(ch);
}//while
}
catch(Exception e){
throw new ServletException(e.toString());
}
finally{
try{if(in!=null)in.close();}catch(Exception e){}
try{if(out!=null)out.close();}catch(Exception e){}
}

}//doGet


现在用户如果下载100M的数据(例如通过Flashget等软件),下到50M的时候,用户中断
数据连接(例如在Flashget里面暂停),现在我的Servlet在while循环内部如果再试图
向out调用write的时候,我期望会捕获到一个IOException,这样我的Servlet线程就可
以及时退出了。但问题是我在Tomcat 4.1里面运行这个Servlet的时候,用户中途中断了
数据连接(100M的50M的时候),我的Servlet还在后台正常的运行,就像什么事情都没
有发生一样,out.write(...)也没有碰到什么异常,传递给write的数据好像被无声无息
的丢弃了――这样就导致了虽然用户在50M处选择了中断,但是我的Servlet却一直要读
完100M才能退出,这样大量的IO资源就被浪费了。

我需要在用户中断数据连接的时候能够得到容器的通知,我该怎么做?

估计是缓冲惹得祸,你在out.write一定次数之后,用out.flush刷新一下。。

希望能行。

好像servlet的io是交给另外一个线程去处理的。
所以servlet的事务会继续处理。

关注

我也正在找这个问题的答案,遇到的问题差不多吧```
呵呵,有没有大虾可以解答一下``!!

在while((ch=in.read())!=-1){
out.write(ch);
}//while
这个循环中,应该做个连接是否存在的判断或干脆sleep一下,否则其他线程无法运行,Tomcat也就无法判断当前连接是否关闭了!