学习了dwr+参考,写的一个Extjs做前端的在线聊天系统

        前些时间学习dwr,参考被人,自己做了一个在线一对一的网络聊天程序,程序界面使用Extjs,后台使用了struts2,hibernate3,数据库mysql。

分享下,望评点。

主要代码:

package com.webca.actions;



import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;

import com.webca.dao.Message;



public class ChatManager {

	public String updateUsersList(String username, HttpServletRequest request) {
		WebContextFactory.get().getScriptSession()
				.setAttribute("username", username);
		System.out.println("****新用户登录:"+username+"  用户ScriptSession: "+WebContextFactory.get().getScriptSession().getId());
		ServletContext sc = request.getSession().getServletContext();
		ServerContext sctx = ServerContextFactory.get(sc);
		// 获得当前浏览 main.jsp 页面的所有脚本session
		Collection sessions = sctx.getScriptSessionsByPage("/webca/main.jsp");
		ScriptSession updateSS=null;
		Iterator it=sessions.iterator();
		for(int i=0;it.hasNext();i++){
			updateSS=(ScriptSession) it.next();
			System.out.println(i+"、****在线用户:"+updateSS.getAttribute("username")+"用户ScriptSession: "+updateSS.getId());
		}
		Util util = new Util(sessions);
		util.addFunctionCall("reloadTree");
		return "";
	}

	/**
	 * 发送消息
	 * 
	 * @param sender    发送者
	 * @param receiver   接收者
	 * @param text  消息内容
	 * @param request
	 */
	public String send(String sender, String receiver, String text,
			HttpServletRequest request) {
		if (text != null) {
			Message msg = new Message();
			msg.setDate(new Date());
			msg.setSender(sender);
			msg.setText(text);
			Collection<ScriptSession> sessions = new HashSet<ScriptSession>();
			sessions.addAll(ServerContextFactory.get(
					request.getSession().getServletContext())
					.getScriptSessionsByPage("/webca/main.jsp"));
			for (ScriptSession session : sessions) {
				String xusername = (String) session.getAttribute("username");
				if (xusername != null && xusername.equals(receiver)) {
					System.out.println("==>单人聊天: 发送用户: "+xusername+"****ScriptSession:  "+session.getId());
					Util fromutil = new Util(session);
					fromutil.addFunctionCall("receiveMessages", msg);
				} else if (xusername != null && xusername.equals(sender)) {
					System.out.println("==>单人聊天:接收用户: "+xusername+"****ScriptSession:  "+session.getId());
					Util toutil = new Util(session);
					toutil.addFunctionCall("receiveMessages", msg);
				}
			}
			System.out.println("==>单人聊天:"+sender+"  向     "+receiver+"   发送信息: "+text);
		}
		return "";
	}

}

本程序可以实现一对一聊天,在同一台电脑上的两个浏览器可以,在局域网的两台电脑也可以,不过有时发送消息会出现问题,不知道是浏览器兼容性的问题,还是代码有些错误,请赐教。。。

界面图片:

扫描二维码关注公众号,回复: 1170984 查看本文章

猜你喜欢

转载自gdzbgg0931.iteye.com/blog/1749350
今日推荐