使用dwr2.0实现服务器推客户端(结合响应socket服务器推消息)

hoar

贡献于2012-04-02

字数:13083 关键词: DWR JavaScript框架

使用dwr2.0实现服务器推客户端(结合响应socket服务器推消息) 1、 在web.xml中配置加入dwr2.0的推功能 Set Character Encoding com.leopard.filters.SetCharacterEncodingFilter encoding UTF-8 struts-cleanup org.apache.struts2.dispatcher.ActionContextCleanUp sitemesh com.opensymphony.module.sitemesh.filter.PageFilter struts2 org.apache.struts2.dispatcher.FilterDispatcher SessionInactivityFilter javawebparts.filter.SessionInactivityFilter forwardTo /errors.jsp 120 SessionInactivityFilter /* Set Character Encoding /* struts-cleanup /* sitemesh /* struts2 /* contextConfigLocation /WEB-INF/classes/com/leopard/spring/applicationContext_*.xml org.springframework.web.context.ContextLoaderListener ************************* dwr-invoker org.directwebremoting.servlet.DwrServlet 调试DWR,发布系统时应将其设为false debug true 使用服务器推技术(反转AJAX) activeReverseAjaxEnabled true initApplicationScopeCreatorsAtStartup true maxWaitAfterWrite 100 4 dwr-invoker /dwr/* **************************** img org.leopard.web.util.AuthImg img /authImg /login/login.jsp 这里与dwr1.0的配置是不一样的 dwr uk.ltd.getahead.dwr.DWRServlet debug true 2、 dwr 的服务器端执行方法代码 package com.leopard.dwr; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.directwebremoting.ScriptBuffer; import org.directwebremoting.ScriptSession; import org.directwebremoting.ServerContext; import org.directwebremoting.ServerContextFactory; import org.directwebremoting.WebContextFactory; import org.directwebremoting.proxy.dwr.Util; import com.leopard.web.util.SingletonSocket; /** * 处理聊天相关 * * @author leopard * */ public class ChatManager { /** 保存当前在线用户列表 */ public static List users = new ArrayList(); /** 保存当前的scriptsession*/ public static Map scriptmap = new HashMap(); /** 保存当前的user和session对应*/ public static Map userScriptMap = new HashMap(); /** * 更新在线用户列表 * @param username 待添加到列表的用户名 * @param flag 是添加用户到列表,还是只获得当前列表 * @param request * @return 用户userid */ public String updateUsersList(String username, boolean flag, HttpServletRequest request) { System.out.println("进入\\....."); User user = null; if (flag) { // 这里取会话(HttpSession)的id为用户id user = new User(request.getSession().getId(), username); //保存用户到列表 users.add(user); //将用户id和页面脚本session绑定 this.setScriptSessionFlag(user.getUserid()); //将用户和页面sessio绑定 this.setUserScriptSession(user); } Util util = new Util(this.leopardScriptSessions(request)); //处理这些页面中的一些元素 util.removeAllOptions("users"); util.addOptions("users", users, "username"); util.removeAllOptions("receiver"); util.addOptions("receiver", users,"userid","username"); if(!flag){ return null; } return user.getUserid(); } /** * 获得当前在线的scriptsession列表(解决了刷新改变scriptsession的问题) * @param request * @return */ public Collection leopardScriptSessions(HttpServletRequest request){ //获得scriptSession,把httpsession和scriptSession存到map中 ScriptSession scriptSession = WebContextFactory.get().getScriptSession(); scriptmap.put(request.getSession().getId(), scriptSession); Collection sessions = new HashSet(); sessions.addAll(scriptmap.values()); return sessions; } /** * 绑定用户名和scriptsession * @param user */ public void setUserScriptSession(User user){ userScriptMap.put(user.getUsername(),WebContextFactory.get().getScriptSession() ); } /** * 将用户id和页面脚本session绑定 * @param userid */ public void setScriptSessionFlag(String userid) { WebContextFactory.get().getScriptSession().setAttribute("userid", userid); } /** * 根据用户id获得指定用户的页面脚本session * @param userid * @param request * @return */ @SuppressWarnings("unchecked") public ScriptSession getScriptSession(String userid, HttpServletRequest request) { ScriptSession scriptSessions = null; Collection sessions = new HashSet(); sessions.addAll(ServerContextFactory.get(request.getSession().getServletContext()) .getScriptSessionsByPage("/leopardweb/main/main.jsp")); for (ScriptSession session : sessions) { String xuserid = (String) session.getAttribute("userid"); if (xuserid != null && xuserid.equals(userid)) { scriptSessions = session; } } return scriptSessions; } public void cleanSession(String userid , HttpServletRequest request) { users.remove(0); scriptmap.remove(userid); } /** * 发送消息 * @param sender 发送者 * @param receiverid 接收者id * @param msg 消息内容 * @param request */ public void send(String sender,String receiverid,String msg,HttpServletRequest request){ ScriptSession session = this.getScriptSession(receiverid, request); ScriptBuffer script = new ScriptBuffer(); script.appendScript("tempfuc(").appendData("nihao!").appendScript(");"); session.addScript(script); Util util = new Util(session); util.setStyle("showMessage", "display", ""); util.setValue("sender", sender); util.setValue("msg", msg); } @SuppressWarnings("static-access") public void socket() { SingletonSocket.getInstance(); } } 这里的socket连接采用了单例模式,保证整个应用中只有一个连接 package com.leopard.web.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.util.Collection; import org.directwebremoting.ScriptBuffer; import org.directwebremoting.ScriptSession; import com.leopard.dwr.ChatManager; /** * 单例模式的socket的连接方式 * @author leopard * */ public class SingletonSocket { private SingletonSocket() { try { Socket so = new Socket("localhost", 8500); System.out.println("连接服务器。"); InputStream inputStream = so.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader( inputStream)); /** * socket服务器端推数据到socket客户端 */ while (true) { //input.readLine()不能放到判断里面,要不会死锁,最好是在最外面传值给变量 String socketData = input.readLine(); //System.out.println(ChatManager.userScriptMap.size()); ScriptSession session = ChatManager.userScriptMap.get("leopard"); if (session != null ) { ScriptBuffer script = new ScriptBuffer(); script.appendScript("tempfuc(") .appendData(socketData).appendScript(");"); session.addScript(script); } /*Collection col = ChatManager.scriptmap.values(); System.out.println("列表长度:" + col.size()); for (ScriptSession session : col) { ScriptBuffer script = new ScriptBuffer(); script.appendScript("tempfuc(") .appendData(input.readLine()).appendScript(");"); session.addScript(script); }*/ } } catch (IOException e) { e.printStackTrace(); } } private static SingletonSocket socketInstance = null; synchronized public static SingletonSocket getInstance() { if (socketInstance == null) { socketInstance = new SingletonSocket(); } return socketInstance; } } 3、 在dwr。Xml文件中配置 4、 实现socket的服务器推客户端 ///~ socket服务器端代码 /// 实现了定时往socke客户端发送消息 /// @一个线程检查socket客户端的用户连接情况 /// @一个线程往socket客户端发送消息 package com.leopard.socket; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class EchoServer { static List sockets = new ArrayList () ; public EchoServer() { Socket incoming;//客户端的链接; ServerSocket so; //服务器socket try { so = new ServerSocket(8500); System.out.println("等待客户端连接。"); while (true) { try { incoming = so.accept(); sockets.add(incoming); System.out.println("已连接客户端。"); GetInfo gi = new GetInfo(incoming);// 调用线程 ClientClose client = new ClientClose();//调用检查socket连接的线程 } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new EchoServer(); } /** * 从客户端得到信息 * @author Administrator * */ private static class GetInfo implements Runnable { // 线程类 Date now = new Date(System.currentTimeMillis()); private Socket incoming; //客户端的链接; private String s_formClient = null;//从客户端传过来的数据 private BufferedReader buffer_formClient;//从客户端传过来的数据流; Thread thread; PrintWriter out; Timer m_MyTimer=new Timer(); public GetInfo(Socket incoming) { try { this.incoming = incoming; out = new PrintWriter(incoming.getOutputStream(),true);//必须要有true,才会返回到客户端 /**从客户端来的数据*/ buffer_formClient = new BufferedReader(new InputStreamReader(incoming .getInputStream())); thread = new Thread(this); thread.start(); } catch (IOException e) { e.printStackTrace(); } } public void run() { m_MyTimer.schedule(new TimerTask() { public void run() { for(int i=0;i scriptmap = new HashMap(); /** * 获得当前在线的scriptsession列表(解决了刷新改变scriptsession的问题) * @param request * @return */ public Collection leopardScriptSessions(HttpServletRequest request){ //获得scriptSession,把httpsession和scriptSession存到map中 ScriptSession scriptSession = WebContextFactory.get().getScriptSession(); scriptmap.put(request.getSession().getId(), scriptSession); Collection sessions = new HashSet(); sessions.addAll(scriptmap.values()); return sessions; }

下载文档,方便阅读与编辑

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 5 金币 [ 分享文档获得金币 ]
6 人已下载

下载文档

相关文档