当前位置: 首页 > 工具软件 > Auto Comet > 使用案例 >

Comet4jHelloWorld 带参数变动查询

柳浩大
2023-12-01

监听java comet 程序 :

package org.comet4j.demo.helloworld;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;


import org.comet4j.core.CometConnection;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.comet4j.core.event.ConnectEvent;
import org.comet4j.core.listener.ConnectListener;


public class HelloWorld implements ServletContextListener {
private static final String CHANNEL = "hello";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Map<String,String> tempMap = new LinkedHashMap<String, String>();

public void contextInitialized(ServletContextEvent event) {  
CometContext cc = CometContext.getInstance();
cc.registChannel(CHANNEL);  // 注册应用的channel

// CometContext.getInstance().getEngine().addConnectListener(new JoinListener());

Thread helloAppModule = new Thread(new HelloAppModule(), "Sender App Module" );
helloAppModule.setDaemon(true);
helloAppModule.start();
}


class HelloAppModule implements Runnable {
// CometConnection conn = null ;  
// String connId = null ;

public void run() {
while (true) {
try {
Thread.sleep(1000);

// 测试连接数量与连接id 正确性
System.out.println( "------------------" );
for( CometConnection ct : CometContext.getInstance().getEngine().getConnections() ){
System.out.println( ct.getId() );   
}
System.out.println("\\\\\\\\\\\\\\\\\\\\");
for( Map.Entry<String, String> entry : tempMap.entrySet() ){
System.out.println( entry.getKey() );   
}
System.out.println( "------------------" );


CometEngine engine = CometContext.getInstance().getEngine();   

                // 移除废弃的连接
                if( tempMap.size()>engine.getConnections().size() ){
                int tempSize = tempMap.size() ;
                int tempConnectionsSize = engine.getConnections().size() ;
                Map<String,String> tempConvertMap = new LinkedHashMap<String, String>();
                for( CometConnection cc : engine.getConnections() ){
                tempConvertMap.put( cc.getId() , tempMap.get(cc.getId()) );
                 }
                tempMap.clear();
                for( Map.Entry<String, String> entry : tempConvertMap.entrySet() ){
                tempMap.put( entry.getKey() , entry.getValue() );
                 }
                tempConvertMap.clear();
                tempConvertMap = null ;


                }
         
         //   正式逻辑处理代码     
if( tempMap.size()>0 ){
for( Map.Entry<String, String> entry : tempMap.entrySet() ){
if(entry.getValue().equals("1")){  
//   engine.sendToAll(CHANNEL, "温度---" + sdf.format( new Date()) );
engine.sendTo("hello", engine.getConnection(entry.getKey()) , "温度---" + sdf.format( new Date()) );
  
}else{     
// engine.sendToAll(CHANNEL,"压力---" + sdf.format( new Date()) );
engine.sendTo("hello", engine.getConnection(entry.getKey()) , "压力---" + sdf.format( new Date()) );
}
}
}
// }
// engine.sendToAll(CHANNEL, Runtime.getRuntime().freeMemory() / (1024*1024));
//
} catch (Exception ex) {
ex.printStackTrace();
}



}
}

// public void tempConn(CometConnection con , String conId ){
// this.conn = con ;
// this.connId = conId ;
// }
}

// class JoinListener extends ConnectListener {
//        @Override
//        public boolean handleEvent(ConnectEvent anEvent) {  
//                CometConnection conn = anEvent.getConn();  
//                conn.getRequest().getAttribute("");
//                CometContext.getInstance().getEngine().sendTo("hello", conn ,"欢迎上线");
//                CometEngine engine = CometContext.getInstance().getEngine();
//                HelloAppModule tempHelloAppModule = new HelloAppModule();
//                tempHelloAppModule.tempConn(conn,conn.getId());
// Thread helloAppModule = new Thread( tempHelloAppModule , "Sender App Module" );
// helloAppModule.setDaemon(true);
// helloAppModule.start();
//                return true ;
//        }
//    }

public void contextDestroyed(ServletContextEvent arg0) {
System.out.println( CometContext.getInstance().getTimeout() );
}
}


曲线救国 servlet 程序 :


package org.comet4j.demo.helloworld;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.comet4j.core.CometContext;


public class h1 extends HttpServlet {


/**
* Constructor of the object.
*/
public h1() {
super();
}


/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
out.print("    This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}


/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
//        System.out.println( request.getParameter("data") + " - data " );
        HelloWorld.tempMap.put( request.getParameter("conId") , request.getParameter("data") );
//        System.out.println( CometContext.getInstance().getEngine().getConnectionId(request) );
}catch(Exception e){
e.printStackTrace();
}
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
// out.println("<HTML>");
// out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println("  <BODY>");
// out.print("    This is ");
// out.print(this.getClass());
// out.println(", using the POST method");
// out.println("  </BODY>");
// out.println("</HTML>");
// out.flush();
// out.close();
}


/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}


前台 html :   hello.html


<!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/comet4j.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
var conId ;


function init(){
        var kbDom = document.getElementById('kb');
        
        
   JS.Engine.on({  
    start : function(cId, channelList, engine){  
  //    alert('连接已建立,连接ID为:' + cId);  
        conId = cId ;
        funcone() ;
    },  
    stop : function(cause, cId, url, engine){  
  //   alert('连接已断开,连接ID为:' + cId + ',断开原因:' + cause + ',断开的连接地址:'+ url);  
    }  
  });  


        JS.Engine.on({
                hello : function(kb){//侦听一个channel
                    kbDom.innerHTML = kb;
                }
        });
        JS.Engine.start('conn');
}


function funcone(){
     $.ajax({  
            type:"POST",  
            url:"h1",  
            data:{data:'1',conId:conId}, 
            success:function(data,textStatus){  
            }  
     });  
}


function functwo(){
     $.ajax({  
            type:"POST",  
            url:"h1",  
            data:{data:'2',conId:conId},  
            success:function(data,textStatus){  
            }  
     });  
}

</script>
</head>
<body οnlοad="init()">
    <button οnclick="funcone()">温度11111</button>   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   
     <button οnclick="functwo()">压力22222</button>  <br></br><br></br><br></br>
        剩余内存:<span id="kb">...</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
</body>
</html>


web.xml 配置 :


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>
        <description>语言[支持:zh,en,默认:zh,详细http://www.loc.gov/standards/iso639-2/php/English_list.php]</description>
        <param-name>Comet.Language</param-name>
        <param-value>zh</param-value>
</context-param>
<context-param>
        <description>请求超时时间/微妙[默认:5000,1分钟(60000),建议至少设置3秒以上]</description>
        <param-name>Comet.Timeout</param-name>
        <param-value>5000</param-value>
</context-param>
<context-param>
        <description>连接空闲过期时间/微妙[默认:5000,5秒]</description>
        <param-name>Comet.ConnExpires</param-name>
        <param-value>5000</param-value>
</context-param>
<context-param>
        <description>连接检查频率/微妙[默认:5000,5秒]</description>
        <param-name>Comet.ConnFrequency</param-name>
        <param-value>5000</param-value>
</context-param>
<context-param>
        <description>缓存信息过期时间/微妙[默认:60000,1分种]</description>
        <param-name>Comet.CacheExpires</param-name>
        <param-value>60000</param-value>
</context-param>
<context-param>
        <description>缓存信息过期检查频率/微妙[默认:60000,1分种]</description>
        <param-name>Comet.CacheFrequency</param-name>
        <param-value>60000</param-value>
</context-param>
<context-param>
        <description>连接模式[auto(默认)/stream/lpool]</description>
        <param-name>Comet.WorkStyle</param-name>
        <param-value>auto</param-value>
</context-param>
<context-param>
        <description>开启调试[false(默认)/true]</description>
        <param-name>Comet.Debug</param-name>
        <param-value>false</param-value>
</context-param>

<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>
    <servlet-name>h1</servlet-name>
    <servlet-class>org.comet4j.demo.helloworld.h1</servlet-class>
  </servlet>


<servlet-mapping>
<servlet-name>CometServlet</servlet-name>
<url-pattern>/conn</url-pattern>
</servlet-mapping>
  <servlet-mapping>
    <servlet-name>h1</servlet-name>
    <url-pattern>/h1</url-pattern>
  </servlet-mapping>


<listener>
<description>HelloWorld</description>
<listener-class>org.comet4j.demo.helloworld.HelloWorld</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>hello.html</welcome-file>
</welcome-file-list>
</web-app>


,。代码引用别人的,带参数变动是我自己写的,谢谢贡献的兄弟,网上comet4j 资料好少 !




 类似资料: