关于java服务器推送对象到页面上

以tomcat6为例首先下载comet4j-tomcat6.jar和comet4j.jar后将jar报引入工程,然后在tomcat中找到server.xml文件,将文件中的<Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />替换成 <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" redirectPort="8443"/>;
在web.xml中配置<listener>
                <description>Comet4J容器侦听</description>
                <listener-class>org.comet4j.core.CometAppListener</listener-class>
        </listener>
        <servlet>
                <description>默认不用修改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>别名</description>
  <listener-class>实现的类的包明+类名</listener-class>
</listener>

前台html页面
首先在页面引入<script type="text/javascript" src="js/comet4j.js"></script>
名称是:<span id="name"></span> 成绩:<span id="tagCom"></span>


function init(){
var kbDom = document.getElementById("tagCom");
var kdc=document.getElementById("name");
        JS.Engine.on({
          isAlrem : function(non){//侦听一个channel

                   kdc.innerHTML=non.tag;
                   kbDom.innerHTML=non.score;
                  
                }
        });
        JS.Engine.start('conn');
}

后台java代码

public class MessageSender implements ServletContextListener {
private static final String CHANNEL = "isAlrem";

public void contextInitialized(ServletContextEvent arg0) {
     CometContext cc = CometContext.getInstance();
     cc.registChannel(CHANNEL);//注册应用的channel
     Thread sendalrem = new Thread(new SendAlrem(), "");
     sendalrem.setDaemon(true);
     sendalrem.start();

}

class SendAlrem implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(4000);
} catch (Exception ex) {
ex.printStackTrace();
}
OneStrutsAlrem on=new OneStrutsAlrem();
on.setScore(90));
on.setTag("1A1");
CometEngine engine = CometContext.getInstance().getEngine();
//这里必须将对象变成json然后在推送到前台页面上面
engine.sendToAll(CHANNEL,JSONObject.fromObject(on));

}
}
}

public void contextDestroyed(ServletContextEvent arg0) {
}
}

你可能感兴趣的:(对象,comet4j,java服务器推)