简单描述: javascript
comet是用ajax实现的服务器推送,有两种实现comet的方式,长轮询和流,这里只实现长轮询。 php
长轮询的过程:页面发起一个服务器请求,而后服务器一直保持链接打开,直到有数据返回。返回数据以后浏览器关闭链接,随即又发起另外一个服务器请求。这一过程在页面打开期间一直保持接二连三。 css
这种方式节省带宽,而且递归请求(有顺序),跟普通轮询无序相比好不少。 html
testPush.html,内容以下 java
简单描述: jquery
comet是用ajax实现的服务器推送,有两种实现comet的方式,长轮询和流,这里只实现长轮询。 ajax
长轮询的过程:页面发起一个服务器请求,而后服务器一直保持链接打开,直到有数据返回。返回数据以后浏览器关闭链接,随即又发起另外一个服务器请求。这一过程在页面打开期间一直保持接二连三。 浏览器
这种方式节省带宽,而且递归请求(有顺序),跟普通轮询无序相比好不少。 服务器
testPush.html,内容以下 网络
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
30
31
32
33
34
35
36
37
38
39
40
|
<
html
>
<
head
>
<
meta
http-equiv
=
"pragma"
content
=
"no-cache"
>
<
meta
http-equiv
=
"cache-control"
content
=
"no-cache"
>
<
meta
http-equiv
=
"Content-Type"
content
=
"text/html; charset=utf-8"
/>
<
script
type
=
"text/javascript"
src
=
"jquery.min.js"
></
script
>
<
script
type
=
"text/javascript"
>
$(function () {
(function longPolling() {
alert(Date.parse(new Date())/1000);
$.ajax({
url: "testPush1111.php",
data: {"timed": Date.parse(new Date())/1000},
dataType: "text",
timeout: 5000,//5秒超时,可自定义设置
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#state").append("[state: " + textStatus + ", error: " + errorThrown + " ]<
br
/>");
if (textStatus == "timeout") { // 请求超时
longPolling(); // 递归调用
} else { // 其余错误,如网络错误等
longPolling();
}
},
success: function (data, textStatus) {
$("#state").append("[state: " + textStatus + ", data: { " + data + "} ]<
br
/>");
if (textStatus == "success") { // 请求成功
longPolling();
}
}
});
})();
});
</
script
>
</
head
>
<
body
>
<
div
id
=
"state"
></
div
>
</
body
>
</
html
>
|
testPush.php,内容以下
测试分析
会有几种状况:
1.成功返回,状态码200,而后再次发起长链接
2.超时,取消(canceled)此次长链接,而后再次发起长链接
3.长链接等待中(pending),待服务器响应
testPush.php,内容以下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php
if
(!
$_GET
[
'timed'
])
exit
();
date_default_timezone_set(
"PRC"
);
set_time_limit(0);
//无限请求超时时间
$timed
=
$_GET
[
'timed'
];
while
(true) {
sleep(3);
// 休眠3秒,模拟处理业务等
$i
= rand(0,100);
// 产生一个0-100之间的随机数
if
(
$i
> 20 &&
$i
< 56) {
// 若是随机数在20-56之间就视为有效数据,模拟数据发生变化
$responseTime
= time();
// 返回数据信息,请求时间、返回数据时间、耗时
echo
(
"result: "
.
$i
.
", response time: "
.
$responseTime
.
", request time: "
.
$timed
.
", use time: "
. (
$responseTime
-
$timed
));
exit
();
}
else
{
// 模拟没有数据变化,将休眠 hold住链接
sleep(13);
exit
();
}
}
|
测试分析
会有几种状况:
1.成功返回,状态码200,而后再次发起长链接
2.超时,取消(canceled)此次长链接,而后再次发起长链接
3.长链接等待中(pending),待服务器响应