dwr的Reverse Ajax,新瓶装老酒,其实就是comet技术,即服务端向客户端push js代码,典型的应用场景就是目前比较火的比赛图文直播,还有聊天室等,消息订阅模式的一种实现。
优点:控制权反转,打开一个网页(或进行一次操作)后,订阅了一个消息,一个客户端服务端连接将维持,服务端检测到数据更新,将自动push数据到客户端,这样服务端对于程序调动的灵活性更加大,避免了客户端大量的循环请求数据。
缺点:连接维持,访问数量一大连接数将很快饱和。
关于comet优点比较权威的阐述:Ajax improves single-user responsiveness. Comet improves application responsiveness for collaborative, multi-user applications and does it without the performance headaches associated with intermittent polling.
看一下dwr官方示例,很简单的clock实现:
html代码:
- <input type="button" value="Start / Stop" onclick="Clock.toggle();"/> <h2 id="clockDisplay"></h2>
<input type="button" value="Start / Stop" οnclick="Clock.toggle();"/> <h2 id="clockDisplay"></h2>
js代码就一行,打开相应属性:
dwr.engine.setActiveReverseAjax(true);
服务端clock类:
- public class Clock implements Runnable {
- public Clock() {
- ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
- executor.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS);
- }
- public void run() {
- if (active) {
- setClockDisplay(new Date().toString());
- }
- }
- /**
- * Called from the client to turn the clock on/off
- */
- public synchronized void toggle() {
- active = !active;
- if (active) {
- setClockDisplay("Started");
- }
- else {
- setClockDisplay("Stopped");
- }
- }
- /**
- * Actually alter the clients.
- * @param output The string to display.
- */
- public void setClockDisplay(final String output) {
- String page = ServerContextFactory.get().getContextPath() + "/reverseajax/clock.html";
- Browser.withPage(page, new Runnable() {
- public void run() {
- Util.setValue("clockDisplay", output);
- }
- });
- }
- protected transient boolean active = false;
- }
public class Clock implements Runnable {
public Clock() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS);
}
public void run() {
if (active) {
setClockDisplay(new Date().toString());
}
}
/**
* Called from the client to turn the clock on/off
*/
public synchronized void toggle() {
active = !active;
if (active) {
setClockDisplay("Started");
}
else {
setClockDisplay("Stopped");
}
}
/**
* Actually alter the clients.
* @param output The string to display.
*/
public void setClockDisplay(final String output) {
String page = ServerContextFactory.get().getContextPath() + "/reverseajax/clock.html";
Browser.withPage(page, new Runnable() {
public void run() {
Util.setValue("clockDisplay", output);
}
});
}
protected transient boolean active = false;
}
个人设想:这个特性可以用来远程实时监控服务器运行状态,服务端自定义调用接口,定义一套xml协议来实时传送数据,也可以利用Web Service。