Java--Comet之服务端消息推送

阅读更多

Comet是一种用于web的推送技术,能使服务器能实时地将更新的信息传送到客户端,而无须客户端发出请求,目前有两种实现方式,长轮询和iframe流

一:所需资源

1.comet4j-tomcat7-v0.0.2.jar

2.servlet-api.jar 3.0

二:tomcat 配置(server.xml中启动nio)




三:监听器配置(web.xml)


        org.comet4j.core.CometAppListener
   
   
        CometServlet
        CometServlet
        org.comet4j.core.CometServlet
   
   
        CometServlet
        /conn
   

   
        HelloWorld
        org.comet4j.demo.helloworld.HelloWorld
   

四:服务端代码示例

public class HelloWorld implements ServletContextListener {
        private static final String CHANNEL = "hello";
        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(1000);
                                } catch (Exception ex) {
                                        ex.printStackTrace();
                                }
                                CometEngine engine = CometContext.getInstance().getEngine();
                                engine.sendToAll(CHANNEL, Runtime.getRuntime().freeMemory()/1024);
                        }
                }
        }

        public void contextDestroyed(ServletContextEvent arg0) {

        }
}

五:客户端代码示例





Comet4J Hello World
type="text/javascript" src="js/comet4j.js">

function init(){
        alert(1);
        var kbDom = document.getElementById('kb');
        JS.Engine.on({
                hello : function(kb){//侦听一个channel
                        kbDom.innerHTML = kb;
                }
        });
        JS.Engine.start('conn');
        JS.Engine.on(
        'start',function(cId,channelList,engine){
              alert('连接已建立,连接ID为:' + cId);
        });
}



        剩余内存:...KB



六:开源的Comet框架

1.jetty

2.pushlet

 

你可能感兴趣的:(Java,Comet,框架)