(3)polling方式由浏览器定时向服务端发送ajax请求,询问后台是否有什么内容需要推送,有的话就会由服务端返回推送内容。这种方式和我们直接在页面通过定时器发送ajax请求,然后查询后台是否有变化内容的实现是类似的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<%@ 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
>
|