`
envy2002
  • 浏览: 149349 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

tomcat中的长连接

 
阅读更多

 

  现在有一个项目:

 

 

  需要用到一个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不断开的条件的,所以是个标准的长连接。
分享到:
评论
2 楼 envy2002 2012-10-16  
当然可以了,tomcat中源码你可以看看,只要“欺骗”过去tomcat断开的条件,tomcat的连接是不会断开的。
1 楼 newSaa 2012-08-24  
问一下,可以在 tomcat 建立tcp 长连接吗?

相关推荐

Global site tag (gtag.js) - Google Analytics