java推送Comet_使用Comet4j实现消息推送

public class NewMsgCollector extends ConnectListener implements ServletContextListener {

private static final String CHANNEL = "hello";

public void contextInitialized(ServletContextEvent contextEvent) {

//注册应用的channel

CometContext context = CometContext.getInstance();

context.registChannel(CHANNEL);

//添加监听器

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

engine.addConnectListener(this);

}

public void contextDestroyed(ServletContextEvent contextEvent) {}

public boolean handleEvent(ConnectEvent connEvent) {

final CometConnection conn = connEvent.getConn();

//建立连接和用户的关系

doCache(conn);

final String connId = conn.getId();

/*模拟业务逻辑*/

Timer timer = new Timer(true);

TimerTask task = new TimerTask() {

public void run() {

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

//推送到所有客户端

//engine.sendToAll("hello", connId + " - you have " + ((int)(Math.random() * 9) + 1) + " new message 
");

if (CacheManager.getContent(connId).isExpired()) {

doCache(conn);

}

if (simulateService(String.valueOf(CacheManager.getContent(connId).getValue()))) {

//推送到指定的客户端

engine.sendTo(CHANNEL, engine.getConnection(connId), CacheManager.getContent(connId).getValue()

+ " - you have " + ((int) (Math.random() * 9) + 1) + " new message 
");

}

}

};

timer.schedule(task, 10000, (1000 * 5));

return true;

}

private void doCache(final CometConnection conn) {

Object userId = conn.getRequest().getSession().getAttribute("currentUserId");

if (userId != null) {

CacheManager.putContent(conn.getId(), String.valueOf(userId), CacheConstant.EXPIRE_AFTER_ONE_HOUR);

}

}

/**

* 模拟业务

* 返回true,false

* true即表示需要推送消息,false即不需要推送

*/

private boolean simulateService(String id) {

int flag = (int) Math.round(Math.random());

if (flag == 0) {

System.out.println(id + " - no messge...");

return false;

}

System.out.println(id + " - messge is coming...");

return true;

}

}


版权声明:本文为weixin_30651345原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。