Pushlets - java comet 開發紀錄

Pushlets - java comet

IDEEclipse
APServerTomcat
Java version1.6

解壓縮後
/clientadditional (non-J2SE) clients
/srcall Java sources
/webappspushlet.war file with the examples; also unpacked in the pushlet subdir
/docall documentation
/libthe pushlet.jar and pushletclient.jar libraries
/thirdpartyexternal libraries
2.ajax 使用到的pushlet檔案
ajax-pushlet-client.js
pushlet.properties
sources.properties
pushlet.jar
3.針對指定的對象發送,並能傳遞參數(紅字部分為新增)
3.1.修改ajax-pushlet-client.js 新增參數定義
              /** Namespaced Pushlet functions. */
              var PL = {
                       NV_P_FORMAT: 'p_format=xml-strict',
                       ..........
                       state: 1,
      parameters: new Array(new Array),//新增參數定義
                      ……………………..
               // Optionally attach session id
               if (PL.sessionId != null) {
                         url = url + '&p_id=' + PL.sessionId;
                         if (anEvent == 'p_leave') {
                                  PL.sessionId = null;
                         }
                }                   
                // 新增參數加入傳遞
                if(PL.parameters.length > 0) {
                      for (var i = 0; i < PL.parameters.length; i++) {
                           var para = PL.parameters[i];
                           for(var key in para) {
                                 url += "&" + key + "=" + para[key];
                          }
                     }
                }
3.2.修改nl.justobjects.pushlet.core. Session.java將自訂參數內容加入session讓後續可取得自訂內容
   private Event event;     
  public static Session create(String anId,Event anEvent) throws PushletException {
                     Session session;
                     try {
                                session = (Session) onfig.getClass(SESSION_CLASS,"nl.justobjects.pushlet.core.Session").newInstance();
                     } catch (Throwable t) {
                                throw new PushletException("Cannot instantiate Session from config", t);
                     }
                     // Init sessionz
                     session.id = anId;
                     session.controller = Controller.create(session);
                     session.subscriber = Subscriber.create(session);
                     session.event = anEvent;
                     return session;
           }        
           public Event getEvent() {
                     return event;
           }
           public void setEvent(Event anEvent) {
                     event=anEvent;
           }
3.3.修改nl.justobjects.pushlet.core. SessionManager.java 指定對象ID及自訂參數帶入
        public Session createSession(Event anEvent) throws PushletException {
                     // Trivial
                     //return Session.create(createSessionId());
                     return Session.create(anEvent.getField("guid",createSessionId()),anEvent);
}
3.4.新增一支servlet程式繼承nl.justobjects.pushlet.servlet.Pushlet.java將指定對象ID及自訂參數帶入
public class PushServlet extends Pushlet {
           private static final long serialVersionUID = 1L;           
           public PushServlet() {
               super();
           }
           protected void doRequest(Event anEvent, HttpServletRequest request, HttpServletResponse response) {
                     // Must have valid event type.
                     String eventType = anEvent.getEventType();
                     try {
                                // Get Session: either by creating (on Join eventType)
                                // or by id (any other eventType, since client is supposed to have joined).
                                Session session = null;
                                if (eventType.startsWith(Protocol.E_JOIN)) {
                                           // Join request: create new subscriber
                                           session = SessionManager.getInstance().createSession(anEvent);
                                           String userAgent = request.getHeader("User-Agent");
                                           if (userAgent != null) {
                                                     userAgent = userAgent.toLowerCase();
                                           } else {
                                                     userAgent = "unknown";
                                           }
                                           session.setUserAgent(userAgent);
                                } else {
                                           // Must be a request for existing Session
                                           // Get id
                                           String id = anEvent.getField(P_ID);
                                           // We must have an id value
                                           if (id == null) {
                                                     response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No id specified");
                                                     Log.warn("Pushlet: bad request, no id specified event=" + eventType);
                                                     return;
                                           }
                                           // We have an id: get the session object
                                           session = SessionManager.getInstance().getSession(id);
                                           session.setEvent(anEvent);
                                           // Check for invalid id
                                           if (session == null) {
                                                     response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid or expired id: " + id);
                                                     Log.warn("Pushlet:  bad request, no session found id=" + id + " event=" + eventType);
                                                     return;
                                           }
                                }                              
                                Command command = Command.create(session, anEvent, request, response);
                                session.getController().doCommand(command);
                     } catch (Throwable t) {
                                Log.warn("Pushlet:  Exception in doRequest() event=" + eventType, t);
                                t.printStackTrace();
                                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                     }
           }
       }


4.使用方式
4.1.ajax-pushlet-client.jspushlet.propertiessources.propertiespushlet.jar放置對應位置。
例如:Eclipse
ajax-pushlet-client.js  à /WebContent/    網頁置放位置
pushlet.propertiessources.properties  à /src/   java原始碼目錄下
pushlet.jar  à/WebContent/WEB-INF/lib  專案引用jar目錄下
4.2.修改web.xml
<servlet>
     <servlet-name>pushlet</servlet-name>
     <servlet-class>新增的servlet路徑PushServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
</servlet>
        <servlet-mapping>
                 <servlet-name>pushlet</servlet-name>
                 <url-pattern>/pushlet.srv</url-pattern>
            </servlet-mapping>
4.3.利用EventPullSource方式進行開發
        public class CometInfo implements Serializable{
           private static final long serialVersionUID = 1L;    
           static public class showInfo extends EventPullSource {
                     @Override
                     protected long getSleepTime() {
                                return 9000; //多久執行一次,單位毫秒
                     }
                     @Override
                     protected Event pullEvent() {
                                Event event = Event.createDataEvent("/event/page");
                                event.setField("INFO","INFO" );
                                return event;
                     }                   
           }
}
將該程式之class名稱(含完整路徑)加入sources.properties
source1=com.boxmylife.events.box.CometInfo$showInfo
4.4.前端使用方式
ajax-pushlet-client.js 引用進來
<script type="text/javascript" src="../js/ajax-pushlet-client.js"></script>
                PL.webRoot= "http://127.0.0.1:8080/site";
                PL._init();   
                PL.parameters.push({"guid":"123456789"}); //傳遞自訂參數,參數guid為指定發送的對象ID
                PL.joinListen('/event/page');
                function onData(event) {
                      var message = decodeURIComponent(event.get('INFO')); //解決中文亂碼
                      if(message != null && message != "undefined"){  
                              alert(message);          
                      }
        }


留言

這個網誌中的熱門文章

Tomcat 7.0 JDBC Connection Pool 帳號密碼加密

PM2 (node.js 管理套件) 安裝使用

vb6動態載入ocx控制項