dwr---服务器反推附demo(实现点对点聊天)

来源:互联网 发布:圆点矩阵 编辑:程序博客网 时间:2024/04/29 23:15

直接上代码解释吧-----

1、TestDwrRevAction

//-----------------初始化数据方法

public void initData(String name,HttpServletRequest request) {
  HttpSession session = request.getSession();
  
  ServletContext application = session.getServletContext();
  WebContext wctx = WebContextFactory.get();//
  ScriptSession ss = wctx.getScriptSession();//获取当前操作对象
  Map<String, ScriptSession> map = (Map<String, ScriptSession>) application.getAttribute("ScriptSession");//获取所有操作对象
  if(map==null){
   map = new HashMap<String, ScriptSession>();
  }
  if(null == map.get("name"))
  {
   map.put(name, ss);//name为页面设置的区别用户的标识,将name与其对象的页面对象绑定
  }
  
  application.setAttribute("ScriptSession", map);
 }

 

//消息发送的方法

public void sendMsg(String msg,String cc, HttpServletRequest request)
 {
  HttpSession session = request.getSession();
  
  //管理自身的ScriptSession
  WebContext wctx = WebContextFactory.get();//
  
  /**发送到指定客户端通信**/
  ServletContext application = session.getServletContext();
  Map<String, ScriptSession> scriptSessionMap = (Map<String, ScriptSession>)application.getAttribute("ScriptSession");
  ScriptSession scriptSession = scriptSessionMap.get(cc);//根据姓名cc取出他对于的客户端 进行操作
  Util utils = new Util(scriptSession);
  ScriptBuffer script = new ScriptBuffer();  
        script.appendScript("testrev(")  
                 .appendData(msg)  
                .appendScript(");");    //调前端js脚本
        scriptSession.addScript(script);
        /**发送到指定客户端通信**/

}

 

2、前端方法

//消息发送

function sendMsg()
{
 var tv = $('#t1').val();
 var cc = $('#cc').val();
 //alert(tv);
 testDwrRevAction.sendMsg(tv,cc,function callback(data){

  });
}

//初始化dwr对象

function initData(){
 //*******
 dwr.engine.setActiveReverseAjax(true);
 testDwrRevAction.initData();
}

//供后台调用展示

function testrev(msg)
{
 // alert(msg);
 $("#tr").val(msg);
}

 

 

觉得对大家有帮助的话 就帮忙点击下我的网站吧 呵呵   go去看看

3、配置见demo

 

 4、测试页面

方法: 可在一个或多个浏览器 打开几个http://localhost:8080/dwrev/jsp/dwrev/testdwrRev.jsp

用户id设置为不同的   。  第二行 第一个text 设置发送的内容    第二个text设置接受者的id 

 

觉得对大家有帮助的话 就帮忙点击下我的网站吧 呵呵   go去看看

 

demo地址:http://download.csdn.net/detail/yixi524/5327368

 

原创粉丝点击