小宝

导航

DWR推送

/**
* 向浏览器客户端推送消息
* @param userid 要推送的对象
* @param function 调用JS函数名(默认receiveMessage)
* @param all 是否推送所有人
* @param params 要推送的内容
*/

public static void pushMessage(final String userid, final String function, final boolean all, final Object... params) {

  Browser.withAllSessionsFiltered(

    new ScriptSessionFilter() {
      public boolean match(ScriptSession session) {
        if (session.getAttribute("userid") == null){
          return false;
        }else
          return all ? true : (session.getAttribute("userid")).equals(userid);
        }

    },

    new Runnable() {
      private ScriptBuffer script = new ScriptBuffer();

      public void run() {
        script.appendCall(StringUtils.isBlank(function) ? "receiveMessage" : function, params);
        Collection<ScriptSession> sessions = Browser
          .getTargetSessions();
        for (ScriptSession scriptSession : sessions) {
          scriptSession.addScript(script);
          System.out.println("sendTime: " + new Date().getTime() + "==>" + scriptSession.getAttribute("userid"));
        }
      }
    });
  }

     match方法判断Session是否匹配;

       Browser.getTargetSessions();获取匹配的Session;

     script.appendCall(StringUtils.isBlank(function) ? "receiveMessage" : function, params);//添加js函数及参数

     scriptSession.addScript(script);添加推送

    以上是个人理解,如有问题欢迎提出来纠正!

posted on 2014-03-18 15:19  小宝在线  阅读(398)  评论(0编辑  收藏  举报