`
hedahai119
  • 浏览: 106069 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

一个WebChat的服务(可插拔jetty版module)

阅读更多

1.这个是一个jetty版的web chat server,用的是cometd技术,server push

2.这个还是一个可插拔的模块

3.如果你愿意你可以给他做成jar包形式,用命令来启动(目前只能手动启动)

4.注解是我写的,很垃圾,将就看吧

5.在你的服务器把这个服务起了,在你自己的web项目上加一个chat页面就可以聊天了,可以群聊,也可以私聊

6.全部代码在下面的zip包里面,是一个Myeclipse8.5 的工程,编译环境JDK1.5

7.2010-08-23 加入jar启动模式,里面有配置文件可以配置,server信息和数据库信息

 

代码示例 - 1:server的mian类,直接执行这个类,chat server 就启动了,端口可以自己指定,目前是8000

package com.brandt.main;
/** 
 * @author Dahai He
 * @date 2010-8-9 
 */
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.handler.MovedContextHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.resource.Resource;
import org.mortbay.resource.ResourceCollection;
import org.mortbay.thread.QueuedThreadPool;


public class CometdServer {
	
	public CometdServer(){
		
	}
	
	public static void main(String[] args) throws Exception{
		int port = 8000;
        State state = new State();
        //state.gameServer = args[0];
        Server server = new Server();
        QueuedThreadPool qtp = new QueuedThreadPool();
        qtp.setMinThreads(5);
        qtp.setMaxThreads(200);
        server.setThreadPool(qtp);
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(port);
        server.addConnector(connector);
        SocketConnector bconnector = new SocketConnector();
        bconnector.setPort(port + 1);
        server.addConnector(bconnector);
        ContextHandlerCollection contexts = new ContextHandlerCollection();
        server.setHandler(contexts);
        MovedContextHandler moved = new MovedContextHandler(contexts, "/", "/cometd");
        moved.setDiscardPathInfo(true);
        Context context = new Context(contexts, "/cometd", 1);
        String version = Server.getVersion();
        if("6.1.x".equals(version)){
            version = "6.1-SNAPSHOT";
        }
        context.setBaseResource(new ResourceCollection(new Resource[] {
            Resource.newResource("./src/com/brandt/webapp/")
        }));
        ServletHolder dftServlet = context.addServlet("org.mortbay.jetty.servlet.DefaultServlet", "/");
        dftServlet.setInitOrder(1);
        ServletHolder comet = context.addServlet("org.mortbay.cometd.continuation.ContinuationCometdServlet", "/cometd/*");
        comet.setInitParameter("timeout", "250000");
        comet.setInitParameter("interval", "100");
        comet.setInitParameter("maxInterval", "10000");
        comet.setInitParameter("multiFrameInterval", "1500");
        comet.setInitParameter("JSONCommented", "true");
        comet.setInitParameter("logLevel", "0");
        comet.setInitOrder(2);
        ServletHolder brandtChat = context.addServlet("com.brandt.main.ChatServlet", "/brandtChat");
        brandtChat.setInitOrder(3);
        ServletHolder command = context.addServlet("com.brandt.main.CommandServlet", "/command");
        command.setInitOrder(4);
        server.start();
        ChatServlet ls = (ChatServlet)brandtChat.getServlet();
        ls.setStateObject(state);
        CommandServlet cs = (CommandServlet)command.getServlet();
        cs.setStateObject(state);
//        AbstractBayeux bayeux = ((ContinuationCometdServlet)comet.getServlet()).getBayeux();
//        state._bayeux = bayeux;
	}

}

 代码示例 - 2 : chat service main类,主要用于发送消息

package com.brandt.main;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.cometd.Bayeux;
import org.cometd.Channel;
import org.cometd.Client;
import org.cometd.Message;
import org.cometd.MessageListener;
import org.cometd.RemoveListener;
import org.mortbay.cometd.BayeuxService;
import org.mortbay.log.Log;

/** 
 * @author Dahai He
 * @date 2010-8-9 
 */
@SuppressWarnings("unchecked")
public class ChatService extends BayeuxService {
	
	/**
	 * NOTICE: channel === room
	 * a channel is just a chat room
	 */
	
	//To store the online user for chat room
	//pattern : {"/brandt/chat":{"dermot":"xw4rrgw145a","christophe":"dwtt6dxaw12c"}}
	private ConcurrentMap<String,Map> _members = new ConcurrentHashMap<String,Map>();

	public ChatService(Bayeux bayeux) {	
		super(bayeux, "chat");
		//output the debug info
		Log.info("In ChatService constructor");
		//set callback function for channel "/chat/**"
        subscribe("/chat/**", "trackMembers");
        //set callback function for channel "/service/**"
        subscribe("/service/**", "privateChat");
	}
	
	/**
	 * When somebody join room "/chat/**" will execute this method
	 * use case => tell the joiner, who is already in this room
	 * @param joiner, who join this chat room
	 * @param channel, the room name
	 * @param map, message
	 * @param id, message id
	 */
	public void trackMembers(final Client joiner, final String channel,Object message, final String id) {
	
		clientFilter(joiner);
		
		if (message instanceof Map) {
			Map<String, Object> data = (Map<String, Object>) message;

			if (Boolean.TRUE.equals(data.get("join"))) {
				final Map members = getMembersInChannel(channel);
				final String username = (String) data.get("user");
				//put this new joiner to the member list for this channel
				members.put(username, joiner.getId());
				//add RmoveListener, when this joiner leave tell other members
				joiner.addListener(createRmoveListener(members,channel,id));
				//just for debug, out put the message information
				joiner.addListener(new MessageListener() {
					public void deliver(Client fromClient,
							final Client toClient, Message message) {
						Log.info("message from"+fromClient.getId()+"is "+ message.getData());
					}
				});
				//publish the member information to the channel 
				publishMessage(channel,members.keySet(),id);
			}
		}
	}
	
	/**
	 * when a user join channel "/service/**" will execute this method
	 * use case => when a user want to send a message to a single user
	 * @param source
	 * @param channel
	 * @param data
	 * @param messageId
	 */
	public void privateChat(Client source, String channel, Map data, String messageId){
		SimpleDateFormat dfm = new SimpleDateFormat("HH:mm");

		String roomName = (String)data.get("room");
		Map membersMap = (Map)_members.get(roomName);
		String peerName = (String)data.get("peer");
		String peerId = (String)membersMap.get(peerName);
		if(peerId != null){
			Client peer = getBayeux().getClient(peerId);
			if(peer != null){
				//TODO make chat log, insert the message into DB
				Map message = new HashMap();
			    message.put("chat", data.get("chat"));
			    message.put("user", data.get("user"));
			    message.put("scope", "private");
			    message.put("peer", peerName);
			    message.put("time", dfm.format(new Date()));		    
			    peer.deliver(getClient(), roomName, message, messageId);
			    source.deliver(getClient(), roomName, message, messageId);
			}
		}else{
			Map message = new HashMap();
		    message.put("chat", "SYSTEM : Sorry "+peerName+" is not online now!");
		    message.put("user", data.get("user"));
		    message.put("scope", "private");
		    message.put("peer", peerName);
		    message.put("time", dfm.format(new Date()));	
			source.deliver(getClient(), roomName, message, messageId);
		}
	}
	
	/**
	 * check if the client is null
	 * @param client
	 */
	private void clientFilter(Client client){
		if(client == null){
			return;
		}
	}
	
	/**
	 * get the users in a channel
	 * @param channelName, name of a channel
	 * @return a map
	 */
	private Map getMembersInChannel(String channelName){
		Map m = _members.get(channelName);
		if (m == null) {
			Map new_list = new ConcurrentHashMap();
			m = _members.putIfAbsent(channelName, new_list);
			if (m == null) {
				m = new_list;
			}
		}
		return m;
	}
	
	/**
	 * create a RemoveListener 
         * @param members, members in this channel
	 * @param channelName, channel name
	 * @param id, message id
	 * @return a instance of RemoveListener
	 */
	private RemoveListener createRmoveListener(final Map members,final String channelName,final String id){
		RemoveListener listener = new RemoveListener() {
			public void removed(String clientId, boolean timeout) {
				members.values().remove(clientId);
				Log.info((new StringBuilder()).append("members: ").append(members).toString());
				Channel c = getBayeux().getChannel(channelName, false);
				if (c != null) {
					c.publish(getClient(), members.keySet(), id);
				}
			}
		};
		return listener;
	}
	
	/**
	 * publish message to a channel
	 * @param channelName
	 * @param message
	 * @param messageId
	 */
	private void publishMessage(String channelName,Object message,String messageId){
		getBayeux().getChannel(channelName, false).publish(getClient(),message, messageId);
	}
	
}
 

代码示例 - 3 :前台用于chat的javascript main 文件 jquery-chat.js

// TODO rewrite with widget factory, moving join/leave etc. to widget methods and init block to init
var username;
var tabList = [];
var tab;

jQuery(function(jQuery) {
	
	var last, meta, connected = false;
	
	// let the login user join the chat room
	init();
	// when user close or refresh Browser, let the user out 
	jQuery(window).unload(leave);

	function init() {
		join();
	}

	function join() {
		
		username = jQuery.trim(jQuery("#loginUser").text());
		
		if (!username) {
			alert('Please enter a username!');
			return;
		}

		var url = document.location.protocol +"//"+document.location.hostname+":8000/cometd/cometd";
		
		//connect with chat server
		jQuery.comet.init(url);
		connected = true;

		//subscribe and join
		jQuery.comet.startBatch();
		jQuery.comet.subscribe("/chat/brandt", receive);
		jQuery.comet.publish("/chat/brandt", {
			user : username,
			join : true,
			chat : username + " has joined"
		});
		jQuery.comet.endBatch();

		// handle cometd failures while in the room
		if (meta) {
			jQuery.comet.unsubscribe(meta);
		}
		meta = jQuery.comet.subscribe("/cometd/meta",
				function(e) {
					// console.debug(e);
					if (e.action == "handshake") {
						if (e.reestablish) {
							if (e.successful) {
								jQuery.comet.subscribe("/chat/demo",receive);
								jQuery.comet.publish("/chat/demo", {
									user : username,
									join : true,
									chat : username + " has re-joined"
								});
							}
							receive( {
								data : {
									join : true,
									user : "SERVER",
									chat : "handshake " + e.successful ? "Handshake OK"
											: "Failed"
								}
							});
						}
					} else if (e.action == "connect") {
						if (e.successful && !connected) {
							receive( {
								data : {
									join : true,
									user : "SERVER",
									chat : "reconnected!"
								}
							});
						}
						if (!e.successful && connected) {
							receive( {
								data : {
									leave : true,
									user : "SERVER",
									chat : "disconnected!"
								}
							});
						}
						connected = e.successful;
					}
			 	});
	}
	
	//not been used for now
	function send() {
		var phrase = jQuery("#phrase");
		var text = phrase.val();
		phrase.val("");

		if (!text || !text.length) {
			return false;
		}
		
		var colons = text.indexOf("::");
		if (colons > 0) {
			jQuery.comet.publish("/service/privatechat", {
				room: "/chat/demo", // This should be replaced by the room name
				user: username,
				chat: text.substring(colons + 2),
				peer: text.substring(0, colons)
			});
			alert(colons);
		} else {
			jQuery.comet.publish("/chat/demo", {
				user: username,
				chat: text
			});
		}
//		jQuery.ajax({
//			url:"./test",
//			type:"GET",
//			success:function(data){
//				alert("success");
//			}
//		});
	}
	
	//when user receive messages from server, this method will execute
	function receive(message) {
		if (!message.data) {
			window.console && console.warn("bad message format " + message);
			return;
		}
		/*
		 * if message.data instanceof Array
		 * 		this case is tell you who is online
		 * else
		 * 		this case is receive some messages from server
		 * 		eg: {user=Christophe, peer=Dermot, scope=private, chat=hello}
		 */
		if (message.data instanceof Array) {
			var list = "";
			for ( var i in message.data){
				//filter some bad message, send from iceface framework! Fuck!~
				var roomuser = jQuery.trim(String(message.data[i]));
				var hasF =  roomuser.indexOf("function");
				if(hasF >= 0){
					break;
				}
				//add the online user				
				if(roomuser == username){
					//you can not chat with yourself
					list += roomuser + "<br/>";
				}else{
					list += "<a href='javascript:select(\""+roomuser+"\")'>" + roomuser + "</a><br/>";
				}				
			}
			jQuery('.userList').html(list);
		} else {
			
			var special = message.data.join || message.data.leave;
			var from = message.data.user;
			var to = message.data.peer;
			var text = message.data.chat;
			var time = message.data.time;
			var chat;
			
			//bad message
			if (!text) {
				return;
			}
			
			if(!special){
				var chatdiv1 = jQuery('#chat'+from);
				var chatdiv2 = jQuery('#chat'+to);
				if(chatdiv1.length > 0){
					chat = chatdiv1;
				}else if(chatdiv2.length > 0){
					chat = chatdiv2;
				}else{
					//if this no chatDiv create a new one
					createChatDiv(from);
					chat = jQuery('#chat'+from);
				}
				
				chat.append("<span style='color:#8B4500'>"
						+ time 
						+"</span>&nbsp;"
						+ "<span style='color:#00008b;font-weight:bold;'>"
						+ from
						+ "&nbsp;:&nbsp;</span>" 
						+ "<span>" 
						+ text
						+ "</span><br/>");
				
				chat[0].scrollTop = chat[0].scrollHeight - chat[0].clientHeight;
			}

		}
	}
	
	//leave the chat room
	function leave() {
		if (!username) {
			return;
		}
		if (meta) {
			jQuery.comet.unsubscribe(meta);
		}
		meta = null;
		username = null;
		jQuery.comet.disconnect();
	}
})

//when user click a user name in the "online user list", call this method
function select(name){
	createChatDiv(name);
}

//create a div for chat
function createChatDiv(name){
	var title = "Chat with " + name;
	var content = "<div>"
				+ "  <div id='chat"+name+"' class='chat' style='height:120px;width:260px;border:1px solid rgb(185,201,239);overflow: auto;'></div>"
				+ "  <input type='text' name='chatText' value='' id='chatText-"+name+"'/>"
				+ "  <input type='button' value='Send'  name='sendB' onclick='sendMessage(\""+name+"\")'/>"
				+ "</div>";
	jQuery.messager.lays(300, 200);
    jQuery.messager.show(title, content, 0);    
}

//action for "send" button in chat div
function sendMessage(name){
	var element = jQuery("input[id='chatText-"+name+"']");
	var text = element.val();
	element.val("");
	if (!text || !text.length) {
		return false;
	}
	jQuery.comet.publish("/service/privatechat", {
		room: "/chat/brandt", // This should be replaced by the room name
		user: username,
		chat: text,
		peer: name
	});
}

 代码示例 - 4:用到的javascript清单

<script type="text/javascript" src="./javascripts/jquery-1.4.2.min.js"/>
<script type="text/javascript" src="./javascripts/jquery.messager.js"/>
<script type="text/javascript" src="./javascripts/json2.js"/>
<script type="text/javascript" src="./javascripts/jquery.comet.js"/>
<script type="text/javascript" src="./javascripts/jquery-chat.js"/>
分享到:
评论
2 楼 liushian 2011-10-26  
就是啊,麻烦把web中的相关代码文件也给一份吧
1 楼 luotb 2011-08-17  
附件里面没有和前台相关的文件、?

相关推荐

    openfire webchat开发包

    Webchat是Openfire的一部分,提供了一个基于Web的聊天客户端,用户无需安装任何桌面软件就能通过浏览器进行即时通讯。 在"openfire webchat开发包"中,我们可以找到构建Webchat所需的所有资源和文件。以下是一些...

    fastpath_webchat_war

    【fastpath_webchat_war】是2017年5月4日编译打包的一个专为openfire设计的Web聊天解决方案。这个压缩包的核心文件是`webchat.war`,它是一个基于Java Web应用程序的归档文件,遵循了WAR(Web Application Archive)...

    WebChat源码

    WebChat源码是一个在线通讯解决方案,它整合了openfire、spark和fastpath等多个组件,以实现高效、实时的聊天功能。下面将详细讲解这些组件及其在WebChat中的作用,以及如何在Eclipse环境中进行部署和访问。 首先,...

    webChat使用websocket实现网页多人聊天

    在本项目"webChat"中,我们将探讨如何利用WebSocket技术来构建一个支持多人聊天的网页应用。 一、WebSocket简介 WebSocket是HTML5新增的一项技术,它允许浏览器和服务器进行全双工通信,即双方可以同时发送数据,而...

    openfire的webchat源码真的

    Webchat是Openfire附带的一个Web客户端,它提供了在浏览器中直接使用IM的功能,无需安装任何桌面应用程序。这个"openfire的webchat源码"是一个宝贵的资源,对于想要了解或定制Openfire Webchat的开发者来说尤其有...

    WebChat一个开源好用的在线聊天程序

    WebChat是一款开源的在线聊天程序,它为用户提供了一个实时交流的平台,支持多种功能和定制化需求。开源意味着它的源代码是公开的,允许开发者查看、修改和分发,这促进了社区的协作与创新,同时也使得WebChat具有...

    openfire webchat源码部署相关jar

    WebChat是Openfire附带的一个网页版聊天客户端,允许用户通过浏览器进行实时通信。在部署Openfire WebChat时,需要用到一些特定的JAR文件,这些文件在描述中已经列出,包括jasper.jar、jasper-compiler-jdt.jar、...

    webchat.war 可部署到apache

    webchat.war 可部署到apache 最新编辑成功,亲测可用

    网页聊天webchat

    在ASP.NET中,可以创建一个HttpHandler或WebSocket服务来处理这些异步请求。WebSocket是HTML5引入的一种双向通信协议,特别适合实时聊天应用,因为它可以在客户端和服务器之间建立持久连接,允许双方实时交换数据。 ...

    WebChat.zip

    "WebChat.zip"作为一个即时通讯小demo,它展示了上述技术的综合运用。通过解压并分析项目源码,开发者可以学习到如何构建一个简单的实时聊天应用,从而进一步提升自己的技能。无论是初学者还是经验丰富的开发者,都...

    web聊天(WebChat)

    【Web聊天(WebChat)】是一个基于Microsoft Visual Studio 2005和AjaxPro2技术构建的简单Web聊天系统。这个项目旨在实现一个实时、交互式的在线聊天环境,让用户可以通过网页进行沟通交流。以下是对该系统的技术细节...

    webchat_welivephpwebsocket_websocket_在线客服_

    【标题】"webchat_welivephpwebsocket_websocket_在线客服_" 涉及到的是一个基于PHP和WebSocket技术构建的在线客服系统。这个系统利用WebSocket实现即时通讯,为用户提供实时、高效的在线咨询服务。 【描述】"php ...

    WebChat网页聊天项目

    【标题】"WebChat网页聊天项目"是一个基于Java技术实现的在线聊天应用,结合了Oracle数据库和Tomcat服务器,利用Eclipse开发环境进行构建。这个项目旨在提供一个实时的、用户友好的网络通信平台,允许用户通过网页...

    WebChat-master.7z

    在本项目"WebChat-master"中,开发者利用WebSocket技术构建了一个简单的网页聊天应用。 首先,项目基于SSM(Spring+SpringMVC+Mybatis)框架进行开发。Spring是核心的依赖注入框架,它管理着应用的组件和它们之间的...

    WebChat 聊天器

    【WebChat聊天器】是一个基于WebSocket技术构建的实时聊天应用,它旨在提供丰富的交互功能,如图片分享、群聊与私聊模式切换、消息提醒以及用户上下线状态的实时更新。WebSocket是一种在客户端和服务器之间建立长...

    WebChat_Data.rar

    【标题】"WebChat_Data.rar" 是一个包含C#源码的压缩文件,主要用于微信数据的提取。这个项目是用Visual Studio 2010开发的,因此它提供了在该环境中运行所需的所有必要文件。 【描述】中的"c#源码--微信数据提取--...

    WebChat网页聊天室

    (JDK1.8、Tomcat8、Mysql5.5、SSM)(使用MybatisPlus增强插件、Pagehelper分页、前端使用AmazeUI与部分LayUI)(聊天使用WebSocket进行通信)(使用Shiro做权限控制与安全认证)(包含建表语句)

    Svelte3.x网页聊天实例-svelte.js仿微信PC版聊天svelte-webchat.doc

    Svelte 3.x 网页聊天实例-svelte.js 仿微信 PC 版聊天 svelte-...Svelte-Webchat 是一个功能完备的网页聊天系统,使用了最新的 Svelte 3.x 框架、SvelteKit 框架和 Sass 预处理技术,具有很高的实用价值和参考价值。

Global site tag (gtag.js) - Google Analytics