Commett 4 jを使用してメッセージの転送を実現します.

5696 ワード

Commett 4 J(Commet for Java)は、AJAX(XMLHTTPRequest)に純粋に基づくサーバプッシュフレームであり、メッセージはJSON方式で伝達され、ロングポーリング、ロングコネクション、自動選択の三つの動作モードを備えています.compett 4 jについてもっと多くの情報はここで詳細に展開しません.理解が必要なのはアドレスにアクセスしてください.http://code.google.com/p/comet4j/.
commett 4 jをプロジェクトに使うには、2つのファイルを導入する必要があります.commet 4 j-tomcat 6.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:NewMsg Collect or.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>