Comet4J(Comet for Java)是一个纯粹基于AJAX(XMLHTTPRequest)的服务器推送框架,消息以JSON方式传递,具备长轮询、长连接、自动选择三种工作模式。自己查了很多资料,要是传输一个对象要先把对象转换成json对象,客户端不需要对这个json数据进行转换,由于comet4j.js内部已将json格式转换成javascript对象。不得不说这个comet4j推送很方便,当然这是个人观点。希望大家多交流交流这个插件。下面是我的代码:
Comet4J目前仅支持Tomcat6、7版本,根据您所使用的Tomcat版本下载【comet4j-tomcat6.jar】或【comet4j-tomcat7.jar】文件放置到WEB项目的WEB-INF\lib目录下。
下载【comet4j.js】到您的项目中,比如:WebContent\js目录下。
因为Comet4J工作在NIO方式下,所以我们需要调整服务器连接器配置,更换为NOI连接器。 打开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"/>服务器端代码:
package com.hfxt.action;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import net.sf.json.JSONObject;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.hfxt.entity.Photo;
import com.hfxt.service.PhotoService;
public class PhotoListener implements ServletContextListener{
private static final String CHANNEL = "hello";
private static String fileName="";
private Photo photo;
protected Logger log = LoggerFactory.getLogger(this.getClass());
public static String getFileName() {
return fileName;
}
public static void setFileName(String fileName) {
PhotoListener.fileName = fileName;
}
@Override
public void contextInitialized(ServletContextEvent sce) {
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(3000);
CometEngine engine = CometContext.getInstance().getEngine();
if(!"".equals(fileName)){
ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");//和ssh联合使用的这里获取bean,就是获取这个bean然后把这个photo保存到数据库里。
PhotoService photoService = (PhotoService) ac.getBean("photoService");
photo = new Photo();
photo.setPhotoName(fileName);
photoService.doAddPhoto(photo);
photo = photoService.getPhotoByName(fileName);
engine.sendToAll(CHANNEL,JSONObject.fromObject(photo));
fileName = "";
}
} catch (Exception e) {
e.printStackTrace();
log.info("PhotoListener bug:{}",e);
}
}
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
页面代码:
<script type="text/javascript">
jQuery(document).ready(function($) {
function long_polling() {
JS.Engine.on({
hello : function(data){//侦听一个channl
alert(data.photoName);//获取图片的名称
}
});
JS.Engine.start(‘conn');
}
long_polling();
});
web.xml
<listener></listener>
附带comet4j官网https://code.google.com/p/comet4j/