使用Comet4j实现消息推送
2019独角兽企业重金招聘Python工程师标准>>>
cometjava
Comet4J(Comet for Java)是一个纯粹基于AJAX(XMLHTTPRequest)的服务器推送框架,消息以JSON方式传递,具备长轮询、长连接、自动选择三种工作模式。有关comet4j更多的信息在此不再详细展开,需要了解的请访问地址 http://code.google.com/p/comet4j/。
在项目中使用comet4j需要引入2个文件,comet4j.js、comet4j-tomcat6.jar。下面是一个示例,希望对需要的人有所帮助。不足之处还请大神谅解。
view:hello.jsp
Jsp代码
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>comet</title>
- <script type="text/javascript" src="/comet4j_demo/js/jquery-1.8.0.min.js"></script>
- <script type="text/javascript" src="/comet4j_demo/js/comet4j.js"></script>
- <script type="text/javascript">
- $(function(){
- JS.Engine.on('hello', function(text){
- $("#targetDiv").append("<span id='msgSpan' style='color:red'>" + text + "</span>");
- });
- <%
- String userId = request.getParameter("userId");
- session.setAttribute("currentUserId", userId);
- %>
- JS.Engine.start('conn');
- });
- $(document).ready(function(){
- $("#targetDiv").bind("click", function(){
- //有新消息
- if ($(this).find("span").length > 0) {
- $("div > span").remove();
- }
- });
- });
- </script>
- </head>
- <body>
- <table border="1" width:600px>
- <tr>
- <td>hello comet</td>
- <td><div id="targetDiv" style="width:300px"></div></td>
- </tr>
- </table>
- </body>
- </html>
service code:NewMsgCollector.java
Java代码
- public class NewMsgCollector extends ConnectListener implements ServletContextListener {
- private static final String CHANNEL = "hello";
- @Override
- public void contextInitialized(ServletContextEvent contextEvent) {
- //注册应用的channel
- CometContext context = CometContext.getInstance();
- context.registChannel(CHANNEL);
- //添加监听器
- CometEngine engine = CometContext.getInstance().getEngine();
- engine.addConnectListener(this);
- }
- @Override
- public void contextDestroyed(ServletContextEvent contextEvent) {}
- @Override
- 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() {
- @Override
- public void run() {
- CometEngine engine = CometContext.getInstance().getEngine();
- //推送到所有客户端
- //engine.sendToAll("hello", connId + " - you have " + ((int)(Math.random() * 9) + 1) + " new message <br />");
- 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 <br />");
- }
- }
- };
- 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;
- }
- }
web.xml
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>NewMsgCollector</description>
- <listener-class>NewMsgCollector</listener-class>
- </listener>
转载于:https://my.oschina.net/lvzunwei/blog/1823848
使用Comet4j实现消息推送相关推荐
- java推送Comet_使用Comet4j实现消息推送
public class NewMsgCollector extends ConnectListener implements ServletContextListener { private sta ...
- web端消息推送的方式介绍
1.goeasy 官方地址:http://www.goeasy.io/ 集成简单,自己可以在官网上去看官方文档,12个月免费!值得一试. 2.dwr推送:官方地址http://directwebre ...
- WEB消息推送—GoEasy
web实时推送的技术在大多数项目里面都会用到,尤其是一些实时性要求高的项目,关于这方面的实现技术有许多,类似于webscoket.dwr.comet4j和netpush等等,其中在以往的篇幅里我也介绍 ...
- iOS消息推送机制的实现
iOS消息推送的工作机制可以简单的用下图来概括: Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务 ...
- 未读消息(小红点),前端 与 RabbitMQ 实时消息推送实践,贼简单~
前几天粉丝群里有个小伙伴问过:web 页面的未读消息(小红点)怎么实现比较简单,刚好本周手头有类似的开发任务,索性就整理出来供小伙伴们参考,没准哪天就能用得上呢. 之前在 <springboot ...
- 友盟小米收不到推送消息_Android 手机收不到消息推送的设置指南 - 融云 RongCloud...
如何解决 Android 手机因推送权限问题收不到消息提醒? 问题描述 部分 Android 手机系统在黑屏待机后自动清理后台运行的软件,这样影响了应用正常接收新的消息,需要开启手机的某些权限.此文档 ...
- iOS 消息推送原理及实现总结
一.消息推送原理: 在实现消息推送之前先提及几个于推送相关概念,如下图: 1. Provider:就是为指定IOS设备应用程序提供Push的服务器,(如果IOS设备的应用程序是客户端的话,那么Prov ...
- 安卓消息推送解决方案
一.推送工具使用 我们在做安卓开发的时候,通常需要一些消息推送功能,我个人平时用的是极光推送,极光推送(JPush)是一个端到端的推送服务,使得服务器端消息能够及时地推送到终端用户手机上,让开发者积极 ...
- 细说 iOS 消息推送
APNS的推送机制 与Android上我们自己实现的推送服务不一样,Apple对设备的控制很严格.消息推送的流程必需要经过APNs: 这里 Provider 是指某个应用的Developer,当然假设 ...
最新文章
- GAN完整理论推导与实现,Perfect!
- pybind11传输文件
- Hadoop系列二:Hadoop单节点伪分布部署并执行mapreduce示例wordcount
- 英文论文中i.e.,e.g.,etc.的正确用法
- activiti自定义流程之Spring整合activiti-modeler5.16实例(四):部署流程定义
- 在Java 8中使用Rhino
- jquery设置宽_JavaScript学习笔记(三十二) jQuery(中)
- leetcode数组汇总_[LeetCode] 300. 最长上升子序列
- java包名和类名可以一样吗_Java入门第三课:Java基本语法
- java mariadb 使用,java连接mariaDB的设置,java连接mariadb
- 昨天刚招到一个程序员,第一天入职就离职了....因为不加班
- ASP.NET页面与IIS底层交互和工作原理详解(一)
- xgboost算法原理_从XGB到SecureBoost:看联邦学习XGB的算法原理
- sql server 存储过程_pgRouting教程七:使用SQL存储过程
- 立陶宛央行抢跑数字货币背后:前瞻的区块链战略 中国已有企业布局
- 以某乎为实战案例,教你用Python爬取手机App数据!居然有人说爬不了APP!
- 為Raspberry Pi 安裝Raspbian系統的詳細步驟 (Mac OS版本)
- SwiftUI学习笔记之@State, @Binding
- error:R3InjectorError(AppModule)[HttpClient -> HttpClient -> HttpClient]:
- excel删除无尽空白行_全了!Excel批量插入空行、批量删除空行、隔行插入空行技巧...
热门文章
- 为 UWP 应用提供的 .NET 网络 API
- PPTPD×××服务器架设
- Hadoop运维记录系列(十二)
- FFmpeg编写一个简单播放器 -1
- 软件架构的相关概念小汇
- rust图形编程_国产编程语言“木兰”,你以为是个王者,结果是个玩笑
- Xamarin.Android部署失败
- vrrp广播风暴_企业园区网MSTP+VRRP组合
- 重磅!UCSF的研究者利用脑机接口首次让患者输出完整句子,展现恢复语言沟通的潜力...
- 脑电分析系列[MNE-Python-2]| MNE中数据结构Raw及其用法简介(更新)