使用Comet4j实现消息推送

Comet4J(Comet for Java)是一个纯粹基于AJAX(XMLHTTPRequest)的服务器推送框架,消息以JSON方式传递,具备长轮询、长连接、自动选择三种工作模式。有关comet4j更多的信息在此不再详细展开,需要了解的请访问地址 http://code.google.com/p/comet4j/。

在项目中使用comet4j需要引入2个文件,comet4j.js、comet4j-tomcat6.jar。下面是一个示例,希望对需要的人有所帮助。不足之处还请大神谅解。

view:hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>comet</title>
<script type="text/javascript" src="/comet4j_demo/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="/comet4j_demo/js/comet4j.js"></script>

<script type="text/javascript">
 
$(function(){
    JS.Engine.on('hello', function(text){ 
    	$("#targetDiv").append("<span id='msgSpan' style='color:red'>" + text + "</span>");
    });
    
    <%
    	String userId = request.getParameter("userId");
 		session.setAttribute("currentUserId", userId);
    %>

    JS.Engine.start('conn');
});

$(document).ready(function(){
	$("#targetDiv").bind("click", function(){
		//有新消息
		if ($(this).find("span").length > 0) {
			$("div > span").remove();
		}
	});
}); 

</script>
</head>
<body>
	<table border="1" width:600px>
		<tr>
			<td>hello comet</td>
			<td><div id="targetDiv" style="width:300px"></div></td>
		</tr>
	</table>
</body>
</html>


service code:NewMsgCollector.java

public class NewMsgCollector extends ConnectListener implements ServletContextListener {

	private static final String CHANNEL = "hello";

	@Override
	public void contextInitialized(ServletContextEvent contextEvent) {
		//注册应用的channel
		CometContext context = CometContext.getInstance();
		context.registChannel(CHANNEL);
		
		//添加监听器
		CometEngine engine = CometContext.getInstance().getEngine();
		engine.addConnectListener(this);
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent contextEvent) {}

	@Override
	public boolean handleEvent(ConnectEvent connEvent) {
		final CometConnection conn = connEvent.getConn();
		
		//建立连接和用户的关系
		doCache(conn);

		final String connId = conn.getId();

		/*模拟业务逻辑*/
		Timer timer = new Timer(true);
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				CometEngine engine = CometContext.getInstance().getEngine();
				//推送到所有客户端
				//engine.sendToAll("hello", connId + " - you have " + ((int)(Math.random() * 9) + 1) + " new message <br />");

				if (CacheManager.getContent(connId).isExpired()) {
					doCache(conn);
				}

				if (simulateService(String.valueOf(CacheManager.getContent(connId).getValue()))) {
					//推送到指定的客户端
					engine.sendTo(CHANNEL, engine.getConnection(connId), CacheManager.getContent(connId).getValue()
							+ " - you have " + ((int) (Math.random() * 9) + 1) + " new message <br />");
				}
			}
		};
		timer.schedule(task, 10000, (1000 * 5));
		return true;
	}

	private void doCache(final CometConnection conn) {
		Object userId = conn.getRequest().getSession().getAttribute("currentUserId");
		if (userId != null) {
			CacheManager.putContent(conn.getId(), String.valueOf(userId), CacheConstant.EXPIRE_AFTER_ONE_HOUR);
		}
	}

	/**
	 * 模拟业务
	 * 返回true,false
	 * true即表示需要推送消息,false即不需要推送
	 */
	private boolean simulateService(String id) {
		int flag = (int) Math.round(Math.random());
		if (flag == 0) {
			System.out.println(id + " - no messge...");
			return false;
		}
		System.out.println(id + " - messge is coming...");
		return true;
	}
}


web.xml


	
<listener>
<description>Comet4J容器侦听</description>
<listener-class>org.comet4j.core.CometAppListener</listener-class>
</listener>

<servlet>
<description>Comet连接[默认:org.comet4j.core.CometServlet]</description>
<display-name>CometServlet</display-name>
<servlet-name>CometServlet</servlet-name>
<servlet-class>org.comet4j.core.CometServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>CometServlet</servlet-name>
<url-pattern>/conn</url-pattern>
</servlet-mapping>

<listener>
<description>NewMsgCollector</description>
<listener-class>NewMsgCollector</listener-class>
</listener>





你可能感兴趣的:(java,Comet)