Spring整合DWR comet 实现无刷新 多人聊天室

开发 后端
用dwr的comet(推)来实现简单的无刷新多人聊天室,comet是长连接的一种。通常我们要实现无刷新,一般会使用到Ajax。

用dwr的comet(推)来实现简单的无刷新多人聊天室,comet是长连接的一种。通常我们要实现无刷新,一般会使用到Ajax。Ajax 应用程序可以使用两种基本的方法解决这一问题:一种方法是浏览器每隔若干秒时间向服务器发出轮询以进行更新,另一种方法是服务器始终打开与浏览器的连接并在数据可用时发送给浏览器。***种方法一般利用setTimeout或是setInterval定时请求,并返回***数据,这无疑增加了服务器的负担,浪费了大量的资源。而第二种方法也会浪费服务器资源,长期的建立连接;而相对***种来说,第二种方式会更优于***种方法;这里有一个一对多和多对一的关系,而comet向多个客户端推送数据就是一对多的关系。而具体使用哪种方式,要看你当前的需求而定,没有绝对的。

为什么使用Comet?

轮询方法的主要缺点是:当扩展到更多客户机时,将生成大量的通信量。每个客户机必须定期访问服务器以检查更新,这为服务器资源添加了更多负荷。最坏的一种情况是对不频繁发生更新的应用程序使用轮询,例如一种 Ajax 邮件 Inbox。在这种情况下,相当数量的客户机轮询是没有必要的,服务器对这些轮询的回答只会是 “没有产生新数据”。虽然可以通过增加轮询的时间间隔来减轻服务器负荷,但是这种方法会产生不良后果,即延迟客户机对服务器事件的感知。当然,很多应用程序可以实现某种权衡,从而获得可接受的轮询方法。

尽管如此,吸引人们使用 Comet 策略的其中一个优点是其显而易见的高效性。客户机不会像使用轮询方法那样生成烦人的通信量,并且事件发生后可立即发布给客户机。但是保持长期连接处于打开状态也会消耗服务器资源。当等待状态的 servlet 持有一个持久性请求时,该 servlet 会独占一个线程。这将限制 Comet 对传统 servlet 引擎的可伸缩性,因为客户机的数量会很快超过服务器栈能有效处理的线程数量。

如果本示例结合Jetty应用服务器效果会更好。

开发环境:

System:Windows

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.0.2.8、tomcat6

IDE:eclipse、MyEclipse 8

开发依赖库:

JavaEE5、Spring 3.0.5、dwr 3

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo or http://hoojo.cnblogs.com/

#p#

一、准备工作

1、 下载dwr的相关jar包

https://java.net/downloads/dwr/Development%20Builds/Build%20116/dwr.jar

程序中还需要spring的相关jar包

http://ebr.springsource.com/repository/app/library/version/detail?name=org.springframework.spring&version=3.0.5.RELEASE

需要的jar包如下

 

2、 建立一个WebProject,名称DWRComet

在web.xml中添加dwr、spring配置如下:

  1. <-- 加载Spring容器配置 --> 
  2. <listener> 
  3.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  4. </listener> 
  5.    
  6. <-- 设置Spring容器加载配置文件路径 --> 
  7. <context-param> 
  8.     <param-name>contextConfigLocation</param-name> 
  9.     <param-value>classpath*:applicationContext-*.xml</param-value> 
  10. </context-param> 
  11.    
  12. <listener> 
  13.     <listener-class>org.directwebremoting.servlet.DwrListener</listener-class> 
  14. </listener> 
  15.    
  16. <servlet> 
  17.     <servlet-name>dwr-invoker</servlet-name> 
  18.     <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> 
  19.     <init-param> 
  20.         <param-name>debug</param-name> 
  21.         <param-value>true</param-value> 
  22.     </init-param> 
  23.           
  24.     <-- dwr的comet控制 --> 
  25.     <init-param> 
  26.       <param-name>pollAndCometEnabled</param-name> 
  27.       <param-value>true</param-value> 
  28.     </init-param> 
  29. </servlet> 
  30.    
  31. <servlet-mapping> 
  32.     <servlet-name>dwr-invoker</servlet-name> 
  33.     <url-pattern>/dwr/*</url-pattern> 
  34. </servlet-mapping> 

3、 在src目录加入applicationContext-beans.xml配置,这个配置专门配置bean对象,用来配置需要注入的对象。

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:aop="http://www.springframework.org/schema/aop" 
  5.     xmlns:tx="http://www.springframework.org/schema/tx"   
  6.     xmlns:util="http://www.springframework.org/schema/util" 
  7.     xmlns:context="http://www.springframework.org/schema/context" 
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  10.     http://www.springframework.org/schema/aop   
  11.     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  12.     http://www.springframework.org/schema/tx   
  13.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  14.     http://www.springframework.org/schema/util   
  15.     http://www.springframework.org/schema/util/spring-util-3.0.xsd  
  16.     http://www.springframework.org/schema/context   
  17.     http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
  18. </beans> 

4、 在WEB-INF目录添加dwr.xml文件,基本代码如下

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"> 
  3. <dwr> 
  4. </dwr> 

以上的准备基本完毕,下面来完成无刷新聊天室代码

#p#

二、聊天室相关业务实现

1、 聊天实体类Model

  1. package com.hoo.entity;  
  2.    
  3. import java.util.Date;  
  4.    
  5. /**  
  6.  * <b>function:</b>  
  7.  * @author hoojo  
  8.  * @createDate 2011-6-3 下午06:40:07  
  9.  * @file Message.java  
  10.  * @package com.hoo.entity  
  11.  * @project DWRComet  
  12.  * @blog http://blog.csdn.net/IBM_hoojo  
  13.  * @email hoojo_@126.com  
  14.  * @version 1.0  
  15.  */ 
  16. public class Message {  
  17.     private int id;  
  18.     private String msg;  
  19.     private Date time;  
  20.     //getter、setter  

2、 编写聊天信息的事件

  1. package com.hoo.chat;  
  2.    
  3. import org.springframework.context.ApplicationEvent;  
  4.    
  5. /**  
  6.  * <b>function:</b>发送聊天信息事件  
  7.  * @author hoojo  
  8.  * @createDate 2011-6-7 上午11:24:21  
  9.  * @file MessageEvent.java  
  10.  * @package com.hoo.util  
  11.  * @project DWRComet  
  12.  * @blog http://blog.csdn.net/IBM_hoojo  
  13.  * @email hoojo_@126.com  
  14.  * @version 1.0  
  15.  */ 
  16. public class ChatMessageEvent extends ApplicationEvent {  
  17.    
  18.     private static final long serialVersionUID = 1L;  
  19.    
  20.     public ChatMessageEvent(Object source) {  
  21.         super(source);  
  22.     }  

继承ApplicationEvent,构造参数用于传递发送过来的消息。这个事件需要一个监听器监听,一旦触发了这个事件,我们就可以向客户端发送消息。

3、 发送消息服务类,用户客户端发送消息。dwr需要暴露这个类里面的发送消息的方法

  1. package com.hoo.chat;  
  2.    
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.ApplicationContextAware;  
  6. import com.hoo.entity.Message;  
  7.    
  8. /**  
  9.  * <b>function:</b>客户端发消息服务类业务  
  10.  * @author hoojo  
  11.  * @createDate 2011-6-7 下午02:12:47  
  12.  * @file ChatService.java  
  13.  * @package com.hoo.chat  
  14.  * @project DWRComet  
  15.  * @blog http://blog.csdn.net/IBM_hoojo  
  16.  * @email hoojo_@126.com  
  17.  * @version 1.0  
  18.  */ 
  19. public class ChatService implements ApplicationContextAware {  
  20.     private ApplicationContext ctx;  
  21.     public void setApplicationContext(ApplicationContext ctx) throws BeansException {  
  22.         this.ctx = ctx;  
  23.     }  
  24.       
  25.     /**  
  26.      * <b>function:</b> 向服务器发送信息,服务器端监听ChatMessageEvent事件,当有事件触发就向所有客户端发送信息  
  27.      * @author hoojo  
  28.      * @createDate 2011-6-8 下午12:37:24  
  29.      * @param msg  
  30.      */ 
  31.     public void sendMessage(Message msg) {  
  32.         //发布事件  
  33.         ctx.publishEvent(new ChatMessageEvent(msg));  
  34.     }  

上面的sendMessage需要浏览器客户端调用此方法完成消息的发布,传递一个Message对象,并且是触发ChatMessageEvent事件。

#p#

4、 编写监听器监听客户端是否触发ChatMessageEvent

  1. package com.hoo.chat;  
  2.    
  3. import java.util.Collection;  
  4. import java.util.Date;  
  5. import javax.servlet.ServletContext;  
  6. import org.directwebremoting.ScriptBuffer;  
  7. import org.directwebremoting.ScriptSession;  
  8. import org.directwebremoting.ServerContext;  
  9. import org.directwebremoting.ServerContextFactory;  
  10. import org.springframework.context.ApplicationEvent;  
  11. import org.springframework.context.ApplicationListener;  
  12. import org.springframework.web.context.ServletContextAware;  
  13. import com.hoo.entity.Message;  
  14.    
  15. /**  
  16.  * <b>function:</b>监听客户端事件,想客户端推出消息  
  17.  * @author hoojo  
  18.  * @createDate 2011-6-7 上午11:33:08  
  19.  * @file SendMessageClient.java  
  20.  * @package com.hoo.util  
  21.  * @project DWRComet  
  22.  * @blog http://blog.csdn.net/IBM_hoojo  
  23.  * @email hoojo_@126.com  
  24.  * @version 1.0  
  25.  */ 
  26. @SuppressWarnings("unchecked")  
  27. public class ChatMessageClient implements ApplicationListener, ServletContextAware {  
  28.       
  29.     private ServletContext ctx;  
  30.     public void setServletContext(ServletContext ctx) {  
  31.         this.ctx = ctx;  
  32.     }  
  33.       
  34.     @SuppressWarnings("deprecation")  
  35.     public void onApplicationEvent(ApplicationEvent event) {  
  36.         //如果事件类型是ChatMessageEvent就执行下面操作  
  37.         if (event instanceof ChatMessageEvent) {  
  38.             Message msg = (Message) event.getSource();  
  39.             ServerContext context = ServerContextFactory.get();  
  40.             //获得客户端所有chat页面script session连接数  
  41.    
  42.             Collection<ScriptSession> sessions = context.getScriptSessionsByPage(ctx.getContextPath() + "/chat.jsp");  
  43.             for (ScriptSession session : sessions) {  
  44.                 ScriptBuffer sb = new ScriptBuffer();  
  45.                 Date time = msg.getTime();  
  46.                 String s = time.getYear() + "-" + (time.getMonth() + 1) + "-" +  time.getDate() + " "   
  47.                         +  time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();  
  48.                 //执行setMessage方法  
  49.    
  50.                 sb.appendScript("showMessage({msg: '")  
  51.                 .appendScript(msg.getMsg())  
  52.                 .appendScript("', time: '")  
  53.                 .appendScript(s)  
  54.                 .appendScript("'})");  
  55.                 System.out.println(sb.toString());  
  56.                 //执行客户端script session方法,相当于浏览器执行JavaScript代码  
  57.                   //上面就会执行客户端浏览器中的showMessage方法,并且传递一个对象过去  
  58.    
  59.                 session.addScript(sb);  
  60.             }  
  61.         }  
  62.     }  

上面的代码主要是监听客户端的事件,一旦客户端有触发ApplicationEvent事件或是其子类,就会执行onApplicationEvent方法。代码中通过instanceof判断对象实例,然后再执行。如果有触发ChatMessageEvent事件,就获取所有连接chat.jsp这个页面的ScriptSession。然后像所有的ScriptSession中添加script。这样被添加的ScriptSession就会在有连接chat.jsp的页面中执行。

所以这就是客户端为什么会执行服务器端的JavaScript代码。但前提是需要在web.xml中添加dwrComet配置以及在chat页面添加ajax反转。

5、 下面开始在bean容器和dwr的配置中添加我们的配置

applicationContext-beans.xml配置

  1. <bean id="chatService" class="com.hoo.chat.ChatService"/> 
  2. <bean id="chatMessageClient" class="com.hoo.chat.ChatMessageClient"/> 

上面的chatService会在dwr配置中用到

dwr.xml配置

  1. <allow> 
  2.     <convert match="com.hoo.entity.Message" converter="bean"> 
  3.         <param name="include" value="msg,time" /> 
  4.     </convert> 
  5.    
  6.     <create creator="spring" javascript="ChatService"> 
  7.         <param name="beanName" value="chatService" /> 
  8.     </create> 
  9. </allow> 

charService的sendMessage方法传递的是Message对象,所以要配置Message对象的convert配置。

上面的create的creator是spring,表示在spring容器中拿chatService对象。里面的参数的beanName表示在spring容器中找name等于charService的bean对象。

#p#

6、 客户端chat.jsp页面代码

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %> 
  6.    
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  8. <html> 
  9.   <head> 
  10.     <base href="<%=basePath%>"> 
  11.       
  12.     <title>Chat</title> 
  13.       
  14.     <meta http-equiv="pragma" content="no-cache"> 
  15.     <meta http-equiv="cache-control" content="no-cache"> 
  16.     <meta http-equiv="expires" content="0">      
  17.     <script type="text/javascript" src="${pageContext.request.contextPath }/dwr/engine.js"></script> 
  18.     <script type="text/javascript" src="${pageContext.request.contextPath }/dwr/util.js"></script> 
  19.     <script type="text/javascript" src="${pageContext.request.contextPath }/dwr/interface/ChatService.js"></script> 
  20.     <script type="text/javascript"> 
  21.         function send() {  
  22.             var time = new Date();  
  23.             var content = dwr.util.getValue("content");  
  24.             var name = dwr.util.getValue("userName");  
  25.             var info = encodeURI(encodeURI(name + " say:\n" + content));  
  26.             var msg = {"msg": info, "time": time};  
  27.             dwr.util.setValue("content", "");  
  28.             if (!!content) {  
  29.                 ChatService.sendMessage(msg);  
  30.             } else {  
  31.                 alert("发送的内容不能为空!");  
  32.             }  
  33.         }  
  34.    
  35.         function showMessage(data) {  
  36.             var message = decodeURI(decodeURI(data.msg));  
  37.             var text = dwr.util.getValue("info");  
  38.             if (!!text) {    
  39.                 dwr.util.setValue("info", text + "\n" + data.time + "  " + message);  
  40.             } else {  
  41.                 dwr.util.setValue("info", data.time + "  " + message);  
  42.             }  
  43.         }  
  44.     </script> 
  45.   </head> 
  46.     
  47.   <body onload="dwr.engine.setActiveReverseAjax(true);"> 
  48.       <textarea rows="20" cols="60" id="info" readonly="readonly"></textarea> 
  49.       <hr/> 
  50.       昵称:<input type="text" id="userName"/><br/> 
  51.       消息:<textarea rows="5" cols="30" id="content"></textarea> 
  52.       <input type="button" value=" Send " onclick="send()" style="height: 85px; width: 85px;"/> 
  53.   </body> 
  54. </html> 

首先,你需要导入dwr的engine.js文件,这个很重要,是dwr的引擎文件。其次你使用的那个类的方法,也需要在导入进来。一般是interface下的,并且在dwr.xml中配置过的create。

上面的js中调用的charService类中的sendMessage方法,所以在jsp页面中导入的是ChatService.js。

在body的onload事件中,需要设置反转Ajax,这个很重要。

showMessage是ChatMessageClient的onApplicationEvent方法中的appendScript中需要执行的方法。data参数也是在那里传递过来的。

每当发送sendMessage方法后就会触发ChatMessageEvent事件,然后监听的地方就会执行onApplicationEvent方法,在这个方法中又会执行浏览器中的showMessage方法。

 

原文链接:http://www.cnblogs.com/hoojo/archive/2011/06/08/2075201.html

【编辑推荐】

  1. Oracle计划修复Java SE中的17个漏洞
  2. Java SE 6新年***次更新 修复Bug超300个
  3. JDK 5和Java SE 6小更新
  4. Java SE 6更新 修复重大安全问题
  5. Java SE 6中的垃圾回收器G1收费是虚惊一场

 

 

责任编辑:艾婧 来源: hoojo的博客
相关推荐

2023-01-13 00:02:41

2023-01-05 09:17:58

2015-07-06 10:42:18

PHP聊天室应用

2011-12-15 11:11:51

JavaNIO

2023-02-10 08:16:48

WebSocket简易聊天室

2022-07-26 14:53:10

WebSocket网络通信协议

2021-11-16 09:38:10

鸿蒙HarmonyOS应用

2022-11-14 08:01:48

2022-12-01 08:25:23

eTsTCP聊天室

2015-08-06 17:17:33

swoole聊天室

2021-10-14 18:46:29

Websocket浏览器API

2011-11-30 16:37:58

sync

2021-11-15 11:32:12

Linux Linux sockeLinux 系统

2022-04-18 10:36:48

社交软件聊天平台rocket.cha

2021-02-06 23:26:25

聊天室开发WebSocket

2021-12-09 16:48:25

鸿蒙HarmonyOS应用

2024-01-18 11:15:46

Pythonsocket聊天室

2012-05-25 10:41:33

StrutsDWRJava

2012-04-12 10:19:08

Ajax.NET
点赞
收藏

51CTO技术栈公众号