当前位置: 代码迷 >> Web前端 >> dwr 2.0兑现网页消息发送(JAVA类)
  详细解决方案

dwr 2.0兑现网页消息发送(JAVA类)

热度:156   发布时间:2012-11-15 15:16:15.0
dwr 2.0实现网页消息发送(JAVA类)

package com.dwrchat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

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

/**
?* 处理聊天相关
?*
?* @author lhq
?*
?*/
public class ChatManager {

?/** 保存当前在线用户列表 */
?public static List<User> users = new ArrayList<User>();//保存所有在线用户
?public static String pageUrl="/Kindergarden/chatroom/chatroom.jsp";
?
?/**
? * 更新在线用户列表
? * @param username 待添加到列表的用户名
? * @param flag 是添加用户到列表,还是只获得当前列表
? * @param request
? * @return 用户userid
? */
?public String updateUsersList(String username, boolean flag, HttpServletRequest request) {
??WebContext webContext = WebContextFactory.get();??
??HttpSession session = webContext.getSession();
??HttpServletResponse response = webContext.getHttpServletResponse();
?? ScriptSession myScSession = webContext.getScriptSession();
??User user = null;
??String result="";
??ServletContext app = webContext.getServletContext();
??boolean resultflag=true;
??if (flag) {?
????
????for(User speaker : users)
????{

//如果有重名的用户则返回错误
?????if(username.equals(speaker.getUsername()))
?????{
??????result="nameerror";
??????return result;
?????}
????}
?????user = new User(String.valueOf(myScSession.hashCode()), username);
?????//保存用户到列表
?????users.add(user);
?????session.setAttribute("speaker",username);
?????session.setAttribute("userid",myScSession.hashCode());
?????// 这里取会话(HttpSession)的id为用户id
?????//将用户id和页面脚本session绑定
?????
?????this.setScriptSessionFlag(user.getUserid());
????
??}
??//更新聊天室
??refresh(request);
???
??ServletContext sc = request.getSession().getServletContext();
??ServerContext sctx = ServerContextFactory.get(sc);
??Collection<ScriptSession> collsession1 = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??ScriptBuffer script = new ScriptBuffer();
??script.appendScript("AddMsg(")
??.appendData("消息")
??.appendScript(",")
??.appendData("")
??.appendScript(",")
??.appendData(app.getAttribute("allContent"))
??.appendScript(",")
??.appendData("")
???? .appendScript(");");
??????? for (ScriptSession ss : collsession1) {
????? ss.addScript(script);
??? }
??/**滚屏函数***/
??????? Collection<ScriptSession> collsessionscroll = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??ScriptBuffer scriptscroll = new ScriptBuffer();
??scriptscroll.appendScript("Scroll(")
???? .appendScript(");");
??????? for (ScriptSession ss : collsessionscroll) {
??????? ?String xuserid = (String) ss.getAttribute("userid");
????? ss.addScript(scriptscroll);
??? }
??if(!flag){
???return null;
??}
??return user.getUserid();
?}
?/**更新聊天室***/
?public void refresh( HttpServletRequest request)
?{
??ServletContext sc = request.getSession().getServletContext();
??ServerContext sctx = ServerContextFactory.get(sc);
??//获得当前浏览 index.jsp 页面的所有脚本session,得到所有登录到该页面的session然后将所有的页面进行更新
??Collection sessions = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??Util util = new Util(sessions);
??
??util.removeAllOptions("users");
??util.addOptions("users", users, "username");
??util.removeAllOptions("receiver");
??util.addOptions("receiver", users,"userid","username");
??
??/**更新在线人数*/
??int totalOnLine=0;
??if(users.size()!=0)
??{
???totalOnLine=users.size();
??}
??util.setValue("WinOnLineNum",totalOnLine);
??
?}
?/**
? * 将用户id和页面脚本session绑定
? * @param userid
? */
?public void setScriptSessionFlag(String userid) {
??if(((String)WebContextFactory.get().getScriptSession().getAttribute("userid"))==null)
??{
???
???WebContextFactory.get().getScriptSession().setAttribute("userid", userid);
??}
??else
??{
???System.out.println("设置User为空");
??}
??
??
?}

?/**
? * 根据用户id获得指定用户的页面脚本session
? * @param userid
? * @param request
? * @return
? */
?
?public ScriptSession getScriptSession(String userid, HttpServletRequest request) {
??
??ScriptSession scriptSessions = null;
??Collection<ScriptSession> collsession1 = new HashSet<ScriptSession>();
??collsession1.addAll(ServerContextFactory.get(request.getSession().getServletContext())
????.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp"));
??/*WebContext context = WebContextFactory.get();
??Collection<ScriptSession> collsession1 = context.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");*/
??for (ScriptSession ss : collsession1) {
???String xuserid = (String) ss.getAttribute("userid");
???
???if (xuserid != null && xuserid.equals(userid)) {
????
????scriptSessions = ss;
???}
??}
??return scriptSessions;
?}
?
?/**
? * 发送消息
? * @param sender 发送者
? * @param receiverid 接收者id
? * @param msg 消息内容
? * @param request
? */
?public void send(String sender,String msg,String nocolormsg,HttpServletRequest request){
??SimpleDateFormat wf = new SimpleDateFormat("EEE");
??java.util.Date date = new java.util.Date();
??java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E");
??String strDate = df.format(date); //当天日期
??WebContext webContext = WebContextFactory.get();??
??HttpSession session = webContext.getSession();
??ServletContext application = webContext.getServletContext();
??String showChat = (String)application.getAttribute("allContent");
??
??if(msg != null)
??{
???String speaker = sender;
???????????????? if(showChat==null||showChat=="")
???????????????? {
?????????????????? int totalMessage=1;
?????????????????? application.setAttribute("allContent",speaker +" 发送时间:"+strDate+" \t\n" + "<br/>"+" \t\n"+msg + "\t\n"+"<br/><br/>");
?????????????????? application.setAttribute("totalMessage",totalMessage);
???????????????? }
???????????????? else
???????????????? {
?????????????????? int lastMessage = (Integer)application.getAttribute("totalMessage");
?????????????????
?????????????????? if(lastMessage<=101)
?????????????????? {
???????????????? ??
???????????????? ?? application.setAttribute("totalMessage",lastMessage+1);
???????????????? ?? application.setAttribute("allContent",showChat + speaker +" 发送时间:"+strDate+ "<br/>"+" \t\n"+msg + "\t\n"+"<br/><br/>");
???????????????? ?
?????????????????? }
?????????????????? else
?????????????????? {
???????????????? ?? application.setAttribute("totalMessage",0);
???????????????? ?? application.setAttribute("allContent","");
???????????????? ?? application.setAttribute("allContent",speaker +" 发送时间:"+strDate+" \t\n" + "<br/>"+" \t\n"+msg + "\t\n"+"<br/>");
?????????????????? }
???????????????? }
???
??}
????
??ServletContext sc = request.getSession().getServletContext();
??ServerContext sctx = ServerContextFactory.get(sc);
??Collection sessions = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??Util util = new Util(sessions);
??//util.setValue("says", application.getAttribute("allContent"));
??
??
??Collection<ScriptSession> collsession1 = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??ScriptBuffer script = new ScriptBuffer();
??script.appendScript("AddMsg(")
??.appendData("消息")
??.appendScript(",")
??.appendData("")
??.appendScript(",")
??.appendData(application.getAttribute("allContent"))
??.appendScript(",")
??.appendData("")
???? .appendScript(");");
??????? for (ScriptSession ss : collsession1) {
????? ss.addScript(script);
??? }
?????
??????? Collection<ScriptSession> collsession2 = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??ScriptBuffer script2 = new ScriptBuffer();
??script2.appendScript("changeTitle(")
??.appendData(sender+"说:"+nocolormsg)
???? .appendScript(");");
??????? for (ScriptSession ss : collsession2) {
????? ss.addScript(script2);
??? }
?}
?//私聊的发送
?public String privateSend(String sender,String receiverid,String msg,HttpServletRequest request){
??SimpleDateFormat wf = new SimpleDateFormat("EEE");
??java.util.Date date = new java.util.Date();
??java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E");
??String strDate = df.format(date); //当天日期
??ServletContext sc = request.getSession().getServletContext();
??ServerContext sctx = ServerContextFactory.get(sc);
??ScriptSession session = this.getScriptSession(receiverid, request);
??Collection<ScriptSession> collsession1 = sctx.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
??ScriptBuffer script = new ScriptBuffer();
??script.appendScript("showView(")
??.appendData(sender)
??.appendScript(",")
??.appendData(receiverid)
??.appendScript(",")
??.appendData(msg)
??.appendScript(",")
??.appendData(strDate)
???? .appendScript(");");
??????? for (ScriptSession ss : collsession1) {
????? ss.addScript(script);
??? }
??/*ScriptSession session = this.getScriptSession(receiverid, request);
??Util util = new Util(session);
??util.addFunctionCall("showView", sender, receiverid, msg, strDate);
?//?util.setValue("MyContent", sender);
*/??return "";
?}
?public String exit(String userid,String username,HttpServletRequest request)
?{
??
??int num=0;
??for(int i=0;i<users.size();i++)
??{
???User user = (User)users.get(i);
???if(userid.equals(user.getUserid()))
???{
????num=i;
???}
??}
??users.remove(num);
??HttpSession session = request.getSession();
??session.invalidate();
??refresh(request);
?
??return userid;
?}
?
?/**
? * 修改昵称
? */
?public String changeName(String userid,String name,HttpServletRequest request)
?{
??String result = "";
??try {
???int num = 0;
???for (int i = 0; i < users.size(); i++) {
????User user = (User) users.get(i);
????if (userid.equals(user.getUserid())) {
?????num = i;
????}
???}
???User user = users.get(num);
???user.setUsername(name);
???refresh(request);
???result="success";
??} catch (Exception e) {
???result="false";
???e.printStackTrace();
??}
??return result;
?}
?
?
?
?public void exitGame(){
??? try {
??
???? WebContext context = WebContextFactory.get();
???? HttpSession httpSession = context.getSession();
???? Integer myScSession = (Integer)httpSession.getAttribute("userid");
???? if (myScSession != null){
????? Collection<ScriptSession> sessions = context.getScriptSessionsByPage("/Kindergarden/chatroom/chatroom.jsp");
????? for (ScriptSession s : sessions){
?????? if (s.hashCode() == myScSession){
??????? s.invalidate();return;
?????? }
?????? else
?????? {
????? ?// System.out.println("myScSession:"+myScSession);
????? ?// System.out.println("hashCode:"+s.hashCode());
????? ?// s.invalidate();
?????? }
????? }
???? }
??? } catch (Exception e) {
???? e.printStackTrace();
??? }
?? }

}

  相关解决方案