javaweb实现后台向前台的消息推送 comet4j

 

1.新建项目,像项目中添加jar包,或者在maven的pom.xml中添加依赖,添加comet4j-tomcat7.jar包

如果不是maven项目,可以将comet4j-tomcat7.jar包放在lib下,如图:

javaweb实现后台向前台的消息推送 comet4j_第1张图片

如果是maven项目,在pom.xml文件中添加依赖,如图:

javaweb实现后台向前台的消息推送 comet4j_第2张图片

 

2.修改tomcat中server.xml配置,protocol="org.apache.coyote.http11.Http11NioProtocol",如下图:

javaweb实现后台向前台的消息推送 comet4j_第3张图片

3.编写后台代码,后台java代码如下

package org.comet4j.demo;

import java.util.Random;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;

public class CometListener implements ServletContextListener{
	private static final String CHANNEL = "test";

    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();
                // 开始发送         
                engine.sendToAll(CHANNEL, getMessage());
            }
        }
    }
    
    public String getMessage(){
    	String[]names = new String[]{"冯春雷","吴兆元","夏胜安","李瑞东","田东东","张文良","刘权","邵帅","肖小良","任银","王继伟"};
    	int number = new Random().nextInt(10) + 1;
    	return names[number];
    }

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}
}

4.配置web.xml,添加监听



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

	
		org.comet4j.demo.CometListener
	
	
		index.html
	

5.编写前台测试页面





Insert title here





	你好:...
	

其中comet4j.js为第三方插件,tomcat用7的版本,具体的源码见链接:

https://download.csdn.net/download/jinxiumeihappy/12113892

你可能感兴趣的:(JAVA,Maven)