现在有一个项目:
需要用到一个http长连接。实现例如像新浪微博的,有新微博来临的提示功能:
其实思路还是比较简单的:
tomcat中的soket连接,是可以做到的。它里面的源码的思路,是有个计数,还有http协议的keep-alive表示,还有
set_time_out的过期时间。这三个参数决定了连接时间的长短,每来一个请求,请求计数减减,见到0断开连接, keep-
alive在http请求中,保持连接,time_out时间是请求最后一次接到请求后,这个time_out时间后,还没有请求,断开连
接。具体思路大概如此,具体情况还要看源码。
那么我们需要在一个action中,用一个死循环hold住这个连接。
如下代码:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try
{
while(true)
{
//in order to test the socket weather is connected,
//when the IOexception happened, let the while quit, determinate the loop.
//don't change this code,otherwise i will kick your ass!!
//bard 2012-01-06
response.flushBuffer();
PrintWriter out=response.getWriter();
out.print("<script>" +
"alert('bard ok');" +
"</script>");
out.flush();
Thread.sleep(3000);
}
}catch (IOException e)
{
System.out.println("client is disconneted!");
}
return null;
}
我采用的是struts1.3。
response.flushBuffer();
的目的就是为了,激发异常,跳出循环,不然这个循环等客户的浏览器关闭的时候,还会一直循环下去,这样不好。
所以要加这个。这就是action能满足tomcat中socket不断开的条件的,所以是个标准的长连接。