需要jdk1.5以上,tomcat5.0以上,具体的安装不再说明。
下载jetty源码,将里面demo的软件包导入到所建的工程,将demo中web路径下org文件夹放在所建工程的webroot下。
将Dojo里面的三个文件夹dijit,dojo,dojox放在webroot路径下。
客户端有两个文件chattest.html,chattest.js。服务端有一个java类ChatTestService.java。
chattest.html
<!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>test chat</title> <script type="text/javascript" src="../dojo/dojo.js" djConfig="parseOnLoad:true"></script> <script type="text/javascript" src="t.js"></script> </head> <body> <div id="root"> <div> <label>一个简单的聊天程序</label> </div> <div id="chat"></div> <div> Chat: <input id="message" type="text" /> <button id="sendChat">Send</button> </div> </div> </body> </html>
chattest.js
dojo.require("dojox.cometd"); dojo.require("dojox.cometd.timestamp"); dojo.require("dojox.cometd.ack"); dojo.require("dojox.cometd.reload"); var root = { _chatSubscription: null, //初始化 _init: function(){ //简历链接,握手 dojox.cometd.init("http://localhost:8080/dojocometd/cometd"); root._subscribe(); //点击按钮时调用_chat方法 dojo.query("#sendChat").onclick(function(e) { root._chat(); }); }, //订阅通道,将信息写到界面 _subscribe: function(){ root._chatSubscription = dojox.cometd.subscribe ('/test/testchat',root._receive); }, //取消订阅 _unsubscribe: function(){ if (room._chatSubscription) { dojox.cometd.unsubscribe(root._chatSubscription); } root._chatSubscription = null; }, //将客户端信息发送到服务器端 _chat:function(){ var text=dojo.byId('message').value; dojox.cometd.publish('/test/testchat', { clientuser: 'test', chatmessageclient: text }); dojo.byId('message').value=""; }, //接受服务器端的信息,显示到界面 _receive: function(message) { var chat = dojo.byId('chat'); var text=message.data.chatmessageservice; chat.innerHTML += "" + "testchat:" + " " + text + "<br/>"; } }; //页面初始渲染时,调用_init方法 dojo.addOnLoad(root, "_init"); //关闭页面时断开链接 dojo.addOnUnload(function() { root._unsubscribe(); dojox.cometd.disconnect(); });
ChatTestService.java
package com.my.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.cometd.bayeux.server.BayeuxServer; import org.cometd.bayeux.server.ConfigurableServerChannel; import org.cometd.bayeux.server.ServerMessage; import org.cometd.bayeux.server.ServerSession; import org.cometd.java.annotation.Configure; import org.cometd.java.annotation.Listener; import org.cometd.java.annotation.Service; import org.cometd.java.annotation.Session; import org.cometd.server.authorizer.GrantAuthorizer; import org.cometd.server.filter.DataFilter; import org.cometd.server.filter.DataFilterMessageListener; import org.cometd.server.filter.JSONDataFilter; import org.cometd.server.filter.NoMarkupFilter; @Service public class ChatTestService { //用来存储订阅了该服务的客户端ID private final List<String> clientId = new ArrayList<String>(); @Inject private BayeuxServer _bayeux; @Session private ServerSession _session; @SuppressWarnings("unused") //配置通道 @Configure("/test/testchat") private void configureTestChat(ConfigurableServerChannel channel) { DataFilterMessageListener noMarkup = new DataFilterMessageListener( _bayeux, new NoMarkupFilter(), new BadWordFilter()); channel.setPersistent(true); channel.addListener(noMarkup); channel.addAuthorizer(GrantAuthorizer.GRANT_PUBLISH); } //通道监听 @Listener("/test/testchat") public void privateTestChat(ServerSession client, ServerMessage message) { //判断list中是否保存了客户端id if (!clientId.contains(client.getId())) clientId.add(client.getId()); //获取客户端数据 Map<String, Object> data = message.getDataAsMap(); //获取所有的client对应的ServerSession ArrayList<ServerSession> ssvs= new ArrayList<ServerSession>( clientId.size()); for (String ssvid: clientId) { if ssvid!= null) { ServerSession ssv = _bayeux.getSession(peerId); if (ssv != null) ssvs.add(ssv); } } if (ssvs.size() > 0) { Map<String, Object> chat = new HashMap<String, Object>(); chat.put("userserivce", data.get("clientuser")); chat.put("chatmessageservice", data.get("chatmessageclient")); ServerMessage.Mutable forward = _bayeux.newMessage(); forward.setChannel("/test/testchat"); forward.setId(message.getId()); forward.setData(chat); //将数据发布到每个订阅的客户端 for (ServerSession ssv: ssvs) if (ssv != client) ssv.deliver(_session, forward); client.deliver(_session, forward); } } class BadWordFilter extends JSONDataFilter { @Override protected Object filterString(String string) { if (string.indexOf("dang") >= 0) throw new DataFilter.Abort(); return string; } } }
配置一下web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <display-name>Cometd Test WebApp</display-name> <!-- Request that Jetty create an MBean to manage the Bayeux instance --> <context-param> <param-name>org.eclipse.jetty.server.context.ManagedAttributes</param-name> <param-value>org.cometd.bayeux,org.cometd.oort.Oort</param-value> </context-param> <!-- Filter to support cross domain requests --> <filter> <filter-name>cross-origin</filter-name> <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class> <!--async-supported>true</async-supported--> </filter> <filter-mapping> <filter-name>cross-origin</filter-name> <url-pattern>/cometd/*</url-pattern> </filter-mapping> <!-- Cometd Servlet --> <servlet> <servlet-name>cometd</servlet-name> <servlet-class>org.cometd.java.annotation.AnnotationCometdServlet</servlet-class> <!--async-supported>true</async-supported--> <init-param> <param-name>timeout</param-name> <param-value>20000</param-value> </init-param> <init-param> <param-name>interval</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>maxInterval</param-name> <param-value>10000</param-value> </init-param> <init-param> <param-name>maxLazyTimeout</param-name> <param-value>5000</param-value> </init-param> <init-param> <param-name>long-polling.multiSessionInterval</param-name> <param-value>2000</param-value> </init-param> <init-param> <param-name>logLevel</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>services</param-name> <param-value>com.my.service.ChatTestService</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cometd</servlet-name> <url-pattern>/cometd/*</url-pattern> </servlet-mapping> </web-app>
将代码发布到tomcat下,访问cometdtest.html文件即可,最好用火狐浏览器