1. 程式人生 > >DWR3.0框架入門(2) —— DWR的伺服器推送

DWR3.0框架入門(2) —— DWR的伺服器推送

1.修改MessagePush中的send方法:
package sugar.dwr;

import java.util.Collection;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;

public class MessagePush {

        public void send(final String content){

              Runnable run = new Runnable(){
                      private ScriptBuffer script = new ScriptBuffer();
                      public void run() {
                            //設定要呼叫的 js及引數
                            script.appendCall("show" , content);
                            //得到所有ScriptSession
                           Collection<ScriptSession> sessions = Browser.getTargetSessions();
                            //遍歷每一個ScriptSession
                            for (ScriptSession scriptSession : sessions){
                                  scriptSession.addScript( script);
                           }
                     }
              };
               //執行推送
              Browser. withAllSessions(run);
       }
}

2.新建receiver.jsp用來接收來自伺服器的訊息:
<%@ page language= "java" import ="java.util.*" pageEncoding="UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head >
    <title >dwr接收</title >
        <script src="js/jquery-1.8.3.js" ></script>
        <script type="text/javascript" src= "dwr/util.js"></script >   
        <script type="text/javascript" src= "dwr/engine.js"></script >
        <script type="text/javascript" src= "dwr/interface/messagePush.js" ></script>
  </head >
 
  <body >
        dwr接收<br />
        <div id="content" style=" width: 200px ;height: 30px;border : 1px solid ; text-align: center ; padding: 5px;"></ div>
        <script type="text/javascript" >
           //這個方法用來啟動該頁面的ReverseAjax功能
           dwr.engine.setActiveReverseAjax( true);
           //設定在頁面關閉時,通知服務端銷燬會話
           dwr.engine.setNotifyServerOnPageUnload( true);
           //這個函式是提供給後臺推送的時候 呼叫的
           function show(content){ 
               $( "#content" ).text(content);
           }
        </script>
  </body >
</html>
測試: 先開啟receiver.jsp,後開啟index.jsp輸入文字後傳送,效果如圖: