comet4j java服務端推送訊息到web頁面執行個體

來源:互聯網
上載者:User

      對於頁面一直監控,以前都是使用ajax請求即可,但是小並發這做法沒多大問題,但是到了大並發就不太合適,如果不想自己寫線程來操控就可以偷懶找一些外掛程式,例如comet4j

下面我來示範下如何使用這個外掛程式

      先準備需要的工具:

comet4j-tomcat6.jar(tomcat6的就匯入這個)

comet4j-tomcat7.jar(tomcat7的就匯入這個)

comet4j.js(頁面引入這個js)

具體操作看下面

然後就寫個class

package com.shadow.extras.comet4j;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 final String CHANNEL2 = "test2";public void contextInitialized(ServletContextEvent arg0) {CometContext cc = CometContext.getInstance();cc.registChannel(CHANNEL);// 註冊應用的channelcc.registChannel(CHANNEL2);Thread helloAppModule = new Thread(new HelloAppModule(),"Sender App Module");// 是否啟動helloAppModule.setDaemon(true);// 啟動線程helloAppModule.start();Thread helloAppModule2 = new Thread(new HelloAppModule2(),"Sender App Module");// 是否啟動helloAppModule2.setDaemon(true);// 啟動線程helloAppModule2.start();}class HelloAppModule2 implements Runnable {public void run() {while (true) {try {// 睡眠時間Thread.sleep(5000);} catch (Exception ex) {ex.printStackTrace();}CometEngine engine = CometContext.getInstance().getEngine();// 擷取訊息內容long l = getFreeMemory();// 開始發送engine.sendToAll(CHANNEL2, l);}}}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, l);}}}public void contextDestroyed(ServletContextEvent arg0) {}public long getFreeMemory() {return Runtime.getRuntime().freeMemory() / 1024;}}

然後再寫個頁面

<!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="plugin/comet4j/comet4j.js"></script><script type="text/javascript">function init(){        var kbDom = document.getElementById('kb');        var kbDom2 = document.getElementById('kb2');        JS.Engine.on({                test : function(aa){//偵聽一個channel                        kbDom.innerHTML = aa;                },                test2 : function(bb){                kbDom2.innerHTML = bb;                }        });        JS.Engine.start('comet');}</script></head><body onload="init()">        剩餘記憶體:<span id="kb">...</span>KB <br/>        剩餘記憶體:<span id="kb2">...</span>KB</body></html>

接著配置下web.xml就ok了

<!-- comet4j --><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>/comet</url-pattern></servlet-mapping><listener><description>TestComet</description><listener-class>com.shadow.extras.comet4j.TestComet</listener-class></listener>

最後修改下tomcat的server.xml檔案

把protocol參數值改成下面的,因為這是基於nio開發的外掛程式

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" redirectPort="8443"/>

測試,很簡單就是訪問我們剛剛建立的test.html,然後就可以看到記憶體數值一直自動重新整理波動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.