使用dwr20实现服务器推客户端_第1页
使用dwr20实现服务器推客户端_第2页
使用dwr20实现服务器推客户端_第3页
使用dwr20实现服务器推客户端_第4页
使用dwr20实现服务器推客户端_第5页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、使用dwr2.0实现服务器推客户端(结合响应socket服务器推消息)1、在 web.xml中配置加入 dwr2.0 的推功能Set Character Encodingcom.leopard.filters.SetCharacterEncodingFilterencodingUTF-8struts-cleanuporg.apache.struts2.dispatcher.ActionContextCleanUp sitemeshcom.opensymphony.module.sitemesh.filter.PageFilter struts2org.apache.struts2.dispat

2、cher.FilterDispatcherSessionInactivityFilterjavawebparts.filter.SessionInactivityFilterforwardTo/errors.jsp 120 SessionInactivityFilter/*Set Character Encoding/*struts-cleanup/*sitemesh/*struts2/*contextConfigLocation/WEB-INF/classes/com/leopard/spring/applicationContext_*.xmlorg.springframework.web

3、.context.ContextLoaderListener!- freemarker 的servletfreemarkercom.opensymphony.webwork.views.freemarker.FreemarkerSe rvlet-*dwr-invokerorg.directwebremoting.servlet.DwrServlet调试DWR,发布系统时应将其设为falsedebugtrue使用服务器推技术(反转AJAX) activeReverseAjaxEnabledtrueinitApplicationScopeCreatorsAtStartuptruemaxWaitAf

4、terWrite1004dwr-invoker/dwr/*imgorg.leopard.web.util.AuthImgimg/authImg!-freemarker*.ftldwr/dwr/*Admin/admin-/login/login.jsp这里与dwr1.0的配置是不一样的dwruk.ltd.getahead.dwr.DWRServletdebugtrue2、dwr的服务器端执行方法代码package com.leopard.dwr;import java.io.BufferedReader;import java.io.IOException;import java.io.Inpu

5、tStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import .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;impor

6、t javax.servlet. HYPERLINK http:/http.HttpServletRequest http.HttpServletRequest;import org.directwebremoting.ScriptBuffer;import org.directwebremoting.ScriptSession;import org.directwebremoting.ServerContext;import org.directwebremoting.ServerContextFactory;import org.directwebremoting.WebContextFa

7、ctory;import xy.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

8、= new HashMap();/*更新在线用户列表*1 param username待添加到列表的用户名*1 param flag是添加用户到列表,还是只获得当前列表*1param request*1 return 用户userid*/pUblic String updateUsersList(String username, boolean flag, HttpServletRequest request) (System. out .println(进入);User user = null;if (flag) (/这里取会话(HttpSession)的id为用户iduser = new

9、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,

10、 users, username);util.removeAllOptions(receiver);util.addOptions(receiver, users,userid,username);if(!flag)(return null;return user.getUserid();/*获得当前在线的scriptsession列表(解决了刷新改变scriptsession的问题)*1param request*1return*/public CollectionleopardScriptSessions(HttpServletRequest request)(/获得 scriptSess

11、ion,把 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*1param user*/publ

12、ic void setUserScriptSession(User user)(userScriptMap.put(user.getUsername(),WebContextFactory.get().getS criptSession();/*将用户id和页面脚本session绑定*1param userid*/public void setScriptSessionFlag(String userid) (WebContextFactory.get().getScriptSession().setAttribute(userid, userid);/*根据用户id获得指定用户的页面脚本se

13、ssion*1param useridrequest*/SuppressWarnings(unchecked)public ScriptSession getScriptSession(String userid, HttpServletRequest request) (ScriptSession scriptSessions = null;Collection sessions = new HashSet();sessions.addAll(ServerContextFactory.get(request.getSession().get ServletContext().getScrip

14、tSessionsByPage(/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 reque

15、st) (users.remove(0);scriptrnap.remove(userid);/*发送消息*Bparam sender 发送者*1 param receiverid 接收者id*1 param msg消息内容*1param request*/public void send(String sender,String receiverid,String msg,HttpServletRequest request)(ScriptSession session = this.getScriptSession(receiverid, request);ScriptBuffer scr

16、ipt = 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() (Single

17、tonSocket.getInstance();这里的socket连接采用了单例模式,保证整个应用中只有一个连接package com.leopard.web.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .Socket;import java.util.Collection;import org.directwebremoting.ScriptBuffer;import org.di

18、rectwebremoting.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 =

19、 new BufferedReader(newInputStreamReader(inputStream);/* socket服务器端推数据到socket客户端*/while (true) (/input.readLine()不能放到判断里面,要不会死锁,最好是在最外面 传值给变量String socketData = input.readLine(); /System.out.println(ChatManager.userScriptMap.size(); ScriptSession session =ChatManager.userScriptMap.get(leopard); if (

20、session != null ) (ScriptBuffer script = new ScriptBuffer(); script.appendScript(tempfuc() .appendData(socketData).appendScript();); session.addScript(script);/*Collection col = ChatManager.scriptmap.values();System.out.println(歹0表长度: + col.size(); for (ScriptSession session : col) (ScriptBuffer scr

21、ipt = 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 (socketins

22、tance = null) (socketinstance = new SingletonSocket(); return socketinstance;3、在dwr。Xml文件中配置 convert converter=bean match=com.leopard.dwr.User/ 4、实现socket的服务器推客户端/ socket服务器端代码/实现了定时往socke客户端发送消息/ 一个线程检查socket客户端的用户连接情况/ 一个线程往socket客户端发送消息package com.leopard.socket;import java.io.*;import .*;import

23、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 .

24、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(

25、); 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 b

26、uffer_formClient; /从客户端传过来的数据流; Thread thread; PrintWriter out;Timer m_MyTimer=new Timer();public GetInfo(Socket incoming) ( try ( this.incoming = incoming; out = newPrintWriter(incoming.getOutputStream(), true); /必须要有 true,才会返回到客 户端/*从客户端来的数据buffer_formClient = new BufferedReader(newInputStreamRead

27、er(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 sockets .size();i+) /利用 For 循环遍历集合Socket s2 = (Socsockets .get(i);/创建Socket对 象S2,强转成Socket,并获取

28、下标 PrintWriter out;try System.out. println(进入发消息);out = new PrintWriter(s2.getOutputStream();out.println(测试。);/打印字符out.flus /刷新该流的缓冲 catch (IOException e) e.printStackTrace();/文本流输出new Date(System.currentTimeMillis () + 1000),10000); private static class ClientClose implements RunnableDate now = new Date(System.currentTimeMillis();Thread thread;PrintWriter out;Timer m_MyTimer=new Timer();pUblic ClientClose() thread = new Thread(this);thread.start();public void run() (m_MyTimer.schedu

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论