javaWeb聊天室简单例子(可私聊)
在下根据网上的相关资料,摸索着写了一个DWR框架推模式的小聊天室,可实现私聊功能。功能基本正常,但是偶尔会出现信息显示不同步的问题,现将源码奉上,希望各位高手能指点一二。ChatManager.java
package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;
import pojo.MessageInfo;
import pojo.UserInfo;
public class ChatManager {
public static List<UserInfo> onlineUsersList=new ArrayList<UserInfo>();
public static List<UserInfo> sendUserList=new ArrayList<UserInfo>();
public static List<MessageInfo> messageList=new ArrayList<MessageInfo>();
public ChatManager(){
UserInfo userInfo = new UserInfo("0","所有人");
sendUserList.add(userInfo);
}
public String updateOnlineUsers(String userName,boolean flag) {
UserInfo userInfo=null;
WebContext context=WebContextFactory.get();
HttpSession session = context.getSession();
if (flag) {
userInfo = new UserInfo(session.getId(),userName);
onlineUsersList.add(userInfo);
sendUserList.add(userInfo);
this.setScriptSessionFlag(userInfo);
}
String currentPage = "/chat/index.jsp";
Collection sessionsByPage = context.getScriptSessionsByPage(currentPage);
Util allPageUtil = new Util(sessionsByPage);
allPageUtil.removeAllOptions("onlineList");
allPageUtil.addOptions("onlineList", onlineUsersList, "userName");
allPageUtil.removeAllOptions("userList");
allPageUtil.addOptions("userList", sendUserList, "userId", "userName");
if (!flag) {
return null;
}
return userInfo.getUserId();
}
public void setScriptSessionFlag(UserInfo userInfo) {
WebContextFactory.get().getScriptSession().setAttribute("userInfo", userInfo);
}
public Collection<ScriptSession> getScriptSessionFlag(String userId) {
Collection<ScriptSession> list=new ArrayList<ScriptSession>();
Collection<ScriptSession> sessions=new ArrayList<ScriptSession>();
WebContext context = WebContextFactory.get();
String currentPage = "/chat/index.jsp";
Collection sessionsByPage = context.getScriptSessionsByPage(currentPage);
sessions.addAll(sessionsByPage);
if ("0".equals(userId)) {
list=sessions;
}else{
for (ScriptSession session : sessions) {
UserInfo userInfo=(UserInfo) session.getAttribute("userInfo");
if (userId.equals(userInfo.getUserId())) {
list.add(session);
break;
}
}
}
return list;
}
public void sendMessage(String sender,String receiverId,String msg) {
Collection<ScriptSession> scriptSessionFlag = this.getScriptSessionFlag(receiverId);
MessageInfo messageInfo = new MessageInfo(sender,receiverId,msg);
messageList.add(messageInfo);
Util receiverUtil = new Util(scriptSessionFlag);
receiverUtil.removeAllOptions("messageList");
receiverUtil.addOptions("messageList", messageList, "msg");
}
}
项目源码下载地址:点击下载
谢谢楼主分享 呃,楼主分享链接失效了
这个项目太棒勒!下下来学习下!
页:
[1]