前言
最近由于工作需要,需要进行web前端的推送方面的调研。由于前端需要对应IE8,所以经过调研选择了comet4j进行web前端的消息推送。这篇文章将调研的结果进行备忘。
项目说明
- 需求:web后端可以将制定信息推送给指定登录用户,用户画面上可以接收到指定的推送。
- 实现:服务器启动后建立一个通道(与前端进行通讯);前端用户登录之后会将登陆Token保存在cookie中;前端建立与后端的连接之后会生成一个通道编号,后端将通道编号与登录用户ID的对应关系缓存起来,以便通过用户ID决定向那个通道发送信息。缓存使用Memcached。
comet4j说明
官网如果不翻墙就不用来了,反正你也看不了
可以到这里来快点戳我
提供一个百度云盘的地址
Comet4J目前仅支持Tomcat6、7版本,根据您所使用的Tomcat版本使用【comet4jtomcat6.jar】或【comet4j-tomcat7.jar】
客户端JS使用【comet4j.js】
使用
- 因为Comet4J工作在NIO方式下,所以我们需要调整服务器连接器配置,更换为NOI连接器。 打开server.xml文件将找到原先的连接器配置:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
修改为:
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" redirectPort="8443"/>
- 修改web.xml文件,增加如下的内容
<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>/conn</url-pattern>
</servlet-mapping>
<!-- 需要自定义的监听器 -->
<listener>
<description>TestComet</description>
<listener-class>com.yun.hcmserver.common.comet4j.Comet4JListener</listener-class>
</listener>
- 后端代码编写
编写Listener:完成Comet通道创建和监听器的注册
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import com.yun.hcmserver.common.utils.ComConst;
/**
* web端推送的监听器
*
* @author linxm
*
*/
public class Comet4JListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
CometContext cc = CometContext.getInstance();
CometEngine engine = cc.getEngine();
// 这里注册应用的通道,在web前端需要有对应的方法检测通道返回的数据
cc.registChannel("message");
// 注册登录监听
engine.addConnectListener(new JoinListener());
// 注册离开监听
engine.addDropListener(new LeftListener());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
编写监听器代码,在前端连接时候触发
public class JoinListener extends ConnectListener {
@Override
public boolean handleEvent(ConnectEvent anEvent) {
CometConnection conn = anEvent.getConn();
HttpServletRequest request = conn.getRequest();
String webToken = "" + CookieUtil.getCookie(ComConst.COOKIE_TOKEN, request);
Object obj = MemcacheUtil.get(webToken);
if(obj != null){
Long userId = (Long)obj;
MemcacheUtil.set(ComConst.COMET4J_KEY + userId, conn.getId());
return true;
}else{
return false;
}
}
}
编写监听器代码,在前端断开时候触发
public class LeftListener extends DropListener {
@Override
public boolean handleEvent(DropEvent anEvent) {
CometConnection conn = anEvent.getConn();
HttpServletRequest request = conn.getRequest();
String webToken = "" + CookieUtil.getCookie(ComConst.COOKIE_TOKEN, request);
Object obj = MemcacheUtil.get(webToken);
if(obj != null){
Long userId = (Long)obj;
MemcacheUtil.deleteCache(ComConst.COMET4J_KEY + userId);
return true;
}else{
return false;
}
}
}
- web端代码
function sendMsg() {
var mail = document.getElementById('mail');
var bell = document.getElementById('bell');
JS.Engine.on({
message : function(kb) {//侦听一个channel,通道名称与后端定义的通道保持一致
mail.innerHTML = kb.mailSize;
bell.innerHTML = kb.bellSize;
},
// 连接触发的方法
start : function(cId,channelList, engine){
console.info("连接信息==" + cId);
},
// 断开触发的方法
stop : function(cause, cId, url, engine){
console.info("断开连接==" + cId);
} });
JS.Engine.start('conn'); // 这里的conn需要与web.xml中的配置保持一致
}
sendMsg();
- 具体发送消息的方法
public static void sendToAll(String channel,Object message){
CometEngine engine = CometContext.getInstance().getEngine();
engine.sendToAll(channel, message);
}
public static void sendToUser(String channel,String userId, Object message){
CometEngine engine = CometContext.getInstance().getEngine();
Object conetId = MemcacheUtil.get(ComConst.COMET4J_KEY + userId);
if(conetId != null){
engine.sendTo(channel, engine.getConnection((String)conetId), message);
}
}
public static void sendToGroup(String channel,String[] userIdArray, Object message){
CometEngine engine = CometContext.getInstance().getEngine();
for(int i=0; i<userIdArray.length; i++){
Object conetId = MemcacheUtil.get(ComConst.COMET4J_KEY + userIdArray[i]);
if(conetId != null){
engine.sendTo(channel, engine.getConnection((String)conetId), message);
}
}
}
补充
一个使用例子请戳这里
配置参数表
<!--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>/conn</url-pattern>
</servlet-mapping>
<!-- Comet4J可选参数配置-->
<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>请求超时时间/微妙[默认:60000,1分钟,建议至少设置3秒以上]</description>
<param-name>Comet.Timeout</param-name>
<param-value>60000</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>