atmosphere使用心得(代貼)

Posted by ayuayu on 2010/03/27

1.代貼
2.引用自https://atmosphere.dev.java.net/nonav/atmosphere_whitepaper.html


以下是官方白皮書所寫

Introduction
The Atmosphere Framework is designed to make it easier to build asynchronous/Comet-based Web applications that include a mix of Comet and RESTful behavior. The Atmosphere Framework is portable and can be deployed on any Web Server that supports the Servlet Specification 2.3. This document introduces the framework and its module.

簡單來說,Atmosphere是一個用來幫助撰寫使用comet技術的網站的Framework,並提供了許多的模組

先拿Atmosphere Runtime來介紹
使用Atmosphere Runtime必須先對container做些設定
至於如何設定, 請參考白皮書及各container的文件


原理


將request送至AtmosphereServlet後
AtmosphereServlet會將request及response交給AtmosphereHandler處理
而AtmosphereHandler為一介面,開發者需實作此介面

AtmosphereHandler需實作的方法如下:
void onRequest(AtmosphereResource<F,G> event);
void onStateChange(AtmosphereResourceEvent<F,G> event);



當request送至AtmosphereHandler, AtmosphereHandler會呼叫onRequest並把此次的request封裝成一事件傳入;而當連線狀態改變時, AtmosphereHandler會呼叫onStateChange並傳入事件

會觸發onStateChange的事件有
Cancel
Timeout
Resuming
Suspend
(使用I/O blocking機制, 詳細解釋可以參考這裡: http://en.wikipedia.org/wiki/Asynchronous_I/O)



3.
使用Atmosphere廣播訊息:
首先, 需先設定web.xml, 把開發者實作的class map至AtmosphereServlet
<servlet>
<servlet-name>AtmosphereServlet</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<init-param>
<param-name>org.atmosphere.useBlocking</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<url-pattern>/bla</url-pattern>
</servlet-mapping>

在AtmosphereResource中用getBroadcaster()取得Broadcaster
並使用Broadcaster.broadcast(Object)即可廣播訊息 (此方法會觸發AtmosphereHandler.onStatechange())

ayuayu個人後文:
如果懶得看參考資料或是看不懂的話,我白話解釋一下
comet就是純網頁卻可以做即時接收資料供javascript跑的技術
一般來說最常用的是flash即時接收後端資料
但是只有網頁的話,由於必須要更新頁面或主動操作或是定期擷取才有辦法從後端拿到資料(就算你用AJAX也一樣),而comet機制就是目前的其中一種解決方案,可以創造一個在當下可以用自訂協定不斷待機等待資料的環境


舉例好了,網頁對戰遊戲如果是純表單,你被攻擊甚至被打死了都一定要你自己按"更新狀態"才會發現變化,但是如果用comet技術,你將可以做出"只要遭受攻擊就會即時看到HP降低"的呈現

沒有留言:

張貼留言