使用Comet为了实现java后台给前台页面推送消息通知
准备
web项目中引入comet4j.js文件和comet4j-tomcat7.jar包
web.xml
修改web.xml,添加以下comet配置
<listener>
<listener-class>org.comet4j.core.CometAppListener</listener-class>
</listener>
<listener>
<description>HelloWorld</description>
<listener-class>com.aerors.listener.TestComet</listener-class>
</listener>
<servlet>
<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>
com.aerors.listener.TestComet
改为实际java类位置
com.aerors.listener.TestComet
package com.aerors.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
public class TestComet implements ServletContextListener {
private static final String CHANNEL = "test";
private static int number1 = 0 ;
public void contextInitialized(ServletContextEvent arg0) {
CometContext cc = CometContext.getInstance();
cc.registChannel(CHANNEL);// 注册应用的channel
Thread helloAppModule = new Thread(new HelloAppModule(),
"Sender App Module");
// 是否启动
helloAppModule.setDaemon(true);
// 启动线程
helloAppModule.start();
}
class HelloAppModule implements Runnable {
public void run() {
while (true) {
try {
// 睡眠时间
Thread.sleep(2000);
} catch (Exception ex) {
ex.printStackTrace();
}
CometEngine engine = CometContext.getInstance().getEngine();
// 获取消息内容
long l = getFreeMemory();
// 开始发送
engine.sendToAll(CHANNEL, number1++);
}
}
}
}
前台页面JSP页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Comet4J Hello World</title>
<script type="text/javascript" src="js/libs/jquery/jquery.min.js"></script>
<script type="text/javascript" src="js/libs/comet4j/comet4j.js"></script>
<script type="text/javascript">
function init(){
var kbDom = document.getElementById('kb');
JS.Engine.on({
test : function(aa){//侦听一个channel
kbDom.innerHTML = aa;
console.log(aa);
}
});
JS.Engine.start('conn');
JS.Engine.on(
'test',function(cId,channelList,engine){
console.dir('连接已建立,连接ID为:' + cId);
});
}
function test(){
var kbDom = document.getElementById('kb');
JS.Engine.start('conn');
JS.Engine.on({
test : function(aa){//侦听一个channel
kbDom.innerHTML = aa;
console.log(aa);
}
});
}
</script>
</head>
<body onload="init();">
<span id="kb">...</span> <br/>
<button onclick="test();">click</button>
</body>
</html>
两种方式加载都可以
注意:前台为动态JSP页面,不能是静态html页面
可以看出请求一直保持,页面上数字也一直在刷新