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代码

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>comet</title>
  8. <script type="text/javascript" src="/comet4j_demo/js/jquery-1.8.0.min.js"></script>
  9. <script type="text/javascript" src="/comet4j_demo/js/comet4j.js"></script>
  10. <script type="text/javascript">
  11. $(function(){
  12. JS.Engine.on('hello', function(text){
  13. $("#targetDiv").append("<span id='msgSpan' style='color:red'>" + text + "</span>");
  14. });
  15. <%
  16. String userId = request.getParameter("userId");
  17. session.setAttribute("currentUserId", userId);
  18. %>
  19. JS.Engine.start('conn');
  20. });
  21. $(document).ready(function(){
  22. $("#targetDiv").bind("click", function(){
  23. //有新消息
  24. if ($(this).find("span").length > 0) {
  25. $("div > span").remove();
  26. }
  27. });
  28. });
  29. </script>
  30. </head>
  31. <body>
  32. <table border="1" width:600px>
  33. <tr>
  34. <td>hello comet</td>
  35. <td><div id="targetDiv" style="width:300px"></div></td>
  36. </tr>
  37. </table>
  38. </body>
  39. </html>

service code:NewMsgCollector.java

Java代码

  1. public class NewMsgCollector extends ConnectListener implements ServletContextListener {
  2. private static final String CHANNEL = "hello";
  3. @Override
  4. public void contextInitialized(ServletContextEvent contextEvent) {
  5. //注册应用的channel
  6. CometContext context = CometContext.getInstance();
  7. context.registChannel(CHANNEL);
  8. //添加监听器
  9. CometEngine engine = CometContext.getInstance().getEngine();
  10. engine.addConnectListener(this);
  11. }
  12. @Override
  13. public void contextDestroyed(ServletContextEvent contextEvent) {}
  14. @Override
  15. public boolean handleEvent(ConnectEvent connEvent) {
  16. final CometConnection conn = connEvent.getConn();
  17. //建立连接和用户的关系
  18. doCache(conn);
  19. final String connId = conn.getId();
  20. /*模拟业务逻辑*/
  21. Timer timer = new Timer(true);
  22. TimerTask task = new TimerTask() {
  23. @Override
  24. public void run() {
  25. CometEngine engine = CometContext.getInstance().getEngine();
  26. //推送到所有客户端
  27. //engine.sendToAll("hello", connId + " - you have " + ((int)(Math.random() * 9) + 1) + " new message <br />");
  28. if (CacheManager.getContent(connId).isExpired()) {
  29. doCache(conn);
  30. }
  31. if (simulateService(String.valueOf(CacheManager.getContent(connId).getValue()))) {
  32. //推送到指定的客户端
  33. engine.sendTo(CHANNEL, engine.getConnection(connId), CacheManager.getContent(connId).getValue()
  34. + " - you have " + ((int) (Math.random() * 9) + 1) + " new message <br />");
  35. }
  36. }
  37. };
  38. timer.schedule(task, 10000, (1000 * 5));
  39. return true;
  40. }
  41. private void doCache(final CometConnection conn) {
  42. Object userId = conn.getRequest().getSession().getAttribute("currentUserId");
  43. if (userId != null) {
  44. CacheManager.putContent(conn.getId(), String.valueOf(userId), CacheConstant.EXPIRE_AFTER_ONE_HOUR);
  45. }
  46. }
  47. /**
  48. * 模拟业务
  49. * 返回true,false
  50. * true即表示需要推送消息,false即不需要推送
  51. */
  52. private boolean simulateService(String id) {
  53. int flag = (int) Math.round(Math.random());
  54. if (flag == 0) {
  55. System.out.println(id + " - no messge...");
  56. return false;
  57. }
  58. System.out.println(id + " - messge is coming...");
  59. return true;
  60. }
  61. }

web.xml

Xml代码

  1. <listener>
  2. <description>Comet4J容器侦听</description>
  3. <listener-class>org.comet4j.core.CometAppListener</listener-class>
  4. </listener>
  5. <servlet>
  6. <description>Comet连接[默认:org.comet4j.core.CometServlet]</description>
  7. <display-name>CometServlet</display-name>
  8. <servlet-name>CometServlet</servlet-name>
  9. <servlet-class>org.comet4j.core.CometServlet</servlet-class>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>CometServlet</servlet-name>
  13. <url-pattern>/conn</url-pattern>
  14. </servlet-mapping>
  15. <listener>
  16. <description>NewMsgCollector</description>
  17. <listener-class>NewMsgCollector</listener-class>
  18. </listener>

转载于:https://my.oschina.net/lvzunwei/blog/1823848

使用Comet4j实现消息推送相关推荐

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

    public class NewMsgCollector extends ConnectListener implements ServletContextListener { private sta ...

  2. web端消息推送的方式介绍

    1.goeasy  官方地址:http://www.goeasy.io/ 集成简单,自己可以在官网上去看官方文档,12个月免费!值得一试. 2.dwr推送:官方地址http://directwebre ...

  3. WEB消息推送—GoEasy

    web实时推送的技术在大多数项目里面都会用到,尤其是一些实时性要求高的项目,关于这方面的实现技术有许多,类似于webscoket.dwr.comet4j和netpush等等,其中在以往的篇幅里我也介绍 ...

  4. iOS消息推送机制的实现

    iOS消息推送的工作机制可以简单的用下图来概括: Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务 ...

  5. 未读消息(小红点),前端 与 RabbitMQ 实时消息推送实践,贼简单~

    前几天粉丝群里有个小伙伴问过:web 页面的未读消息(小红点)怎么实现比较简单,刚好本周手头有类似的开发任务,索性就整理出来供小伙伴们参考,没准哪天就能用得上呢. 之前在 <springboot ...

  6. 友盟小米收不到推送消息_Android 手机收不到消息推送的设置指南 - 融云 RongCloud...

    如何解决 Android 手机因推送权限问题收不到消息提醒? 问题描述 部分 Android 手机系统在黑屏待机后自动清理后台运行的软件,这样影响了应用正常接收新的消息,需要开启手机的某些权限.此文档 ...

  7. iOS 消息推送原理及实现总结

    一.消息推送原理: 在实现消息推送之前先提及几个于推送相关概念,如下图: 1. Provider:就是为指定IOS设备应用程序提供Push的服务器,(如果IOS设备的应用程序是客户端的话,那么Prov ...

  8. 安卓消息推送解决方案

    一.推送工具使用 我们在做安卓开发的时候,通常需要一些消息推送功能,我个人平时用的是极光推送,极光推送(JPush)是一个端到端的推送服务,使得服务器端消息能够及时地推送到终端用户手机上,让开发者积极 ...

  9. 细说 iOS 消息推送

    APNS的推送机制 与Android上我们自己实现的推送服务不一样,Apple对设备的控制很严格.消息推送的流程必需要经过APNs: 这里 Provider 是指某个应用的Developer,当然假设 ...

最新文章

  1. GAN完整理论推导与实现,Perfect!
  2. pybind11传输文件
  3. Hadoop系列二:Hadoop单节点伪分布部署并执行mapreduce示例wordcount
  4. 英文论文中i.e.,e.g.,etc.的正确用法
  5. activiti自定义流程之Spring整合activiti-modeler5.16实例(四):部署流程定义
  6. 在Java 8中使用Rhino
  7. jquery设置宽_JavaScript学习笔记(三十二) jQuery(中)
  8. leetcode数组汇总_[LeetCode] 300. 最长上升子序列
  9. java包名和类名可以一样吗_Java入门第三课:Java基本语法
  10. java mariadb 使用,java连接mariaDB的设置,java连接mariadb
  11. 昨天刚招到一个程序员,第一天入职就离职了....因为不加班
  12. ASP.NET页面与IIS底层交互和工作原理详解(一)
  13. xgboost算法原理_从XGB到SecureBoost:看联邦学习XGB的算法原理
  14. sql server 存储过程_pgRouting教程七:使用SQL存储过程
  15. 立陶宛央行抢跑数字货币背后:前瞻的区块链战略 中国已有企业布局
  16. 以某乎为实战案例,教你用Python爬取手机App数据!居然有人说爬不了APP!
  17. 為Raspberry Pi 安裝Raspbian系統的詳細步驟 (Mac OS版本)
  18. SwiftUI学习笔记之@State, @Binding
  19. error:R3InjectorError(AppModule)[HttpClient -> HttpClient -> HttpClient]:
  20. excel删除无尽空白行_全了!Excel批量插入空行、批量删除空行、隔行插入空行技巧...

热门文章

  1. 为 UWP 应用提供的 .NET 网络 API
  2. PPTPD×××服务器架设
  3. Hadoop运维记录系列(十二)
  4. FFmpeg编写一个简单播放器 -1
  5. 软件架构的相关概念小汇
  6. rust图形编程_国产编程语言“木兰”,你以为是个王者,结果是个玩笑
  7. Xamarin.Android部署失败
  8. vrrp广播风暴_企业园区网MSTP+VRRP组合
  9. 重磅!UCSF的研究者利用脑机接口首次让患者输出完整句子,展现恢复语言沟通的潜力...
  10. 脑电分析系列[MNE-Python-2]| MNE中数据结构Raw及其用法简介(更新)