HTTP 笔记与总结(9)分块传输、持久连接 与 反向 ajax(comet / server push / 服务器推技术)

HTTP 笔记与总结(9)分块传输、持久连接 与 反向 ajax(comet / server push / 服务器推技术)

反向 ajax 又叫 comet / server push / 服务器推技术php

应用范围:网页聊天服务器,例如新浪微博在线聊天、google mail 网页聊天html

原理:通常而言,HTTP 协议的特色是,链接以后断开链接(服务器响应 Content-Length,收到了指定 Length 长度的内容时,也就断开了)。在 HTTP 1.1 协议中,容许不写 Content-Length,好比要发送的内容长度确实不知道,此时须要一个特殊的 Content-Type:chunked,叫作分块传输,只有当服务器最后发送 0\r\n,在代表服务器和客户端的这次链接完全结束。mysql

 

【例】ajax

1sql

2数据库

3浏览器

4服务器

5fetch

6google

7

8

9

10

11

12

13

14

15

16

<?php

set_time_limit(0);

//ob_start();

$pad str_repeat(' ', 4000);

echo $pad,'<br />';

ob_flush();

flush();//把产生的内容当即发送给浏览器而不是等脚本结束再一块儿发送

 

$i = 1;

while($i++){

    echo $pad,'<br>';

    echo $i,'<br>';

    ob_flush();

    flush();

    sleep(1);

}

执行页面:

  

 2,3,4,5..源源不断地输出。

 

 

当输出的值是数据库中的数据(能够是聊天记录),就能够实现即时通讯。 

新建数据库 msg,新建表 message:

1

2

3

4

5

6

CREATE TABLE `message` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `content` varchar(200) NOT NULL COMMENT '聊天内容',

  `flag` int(11) NOT NULL DEFAULT '0' COMMENT '0-未读 1-已读',

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

修改 comet.php: 

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

<?php

set_time_limit(0);

//ob_start();

$pad str_repeat(' ', 4000);

echo $pad,'<br />';

ob_flush();

flush();//把产生的内容当即发送给浏览器而不是等脚本结束再一块儿发送

 

//链接数据库

$conn = mysql_connect('localhost''root''');

mysql_query('use msg');

 

while(1){

    $sql 'select * from message where flag = 0';

    $rs = mysql_query($sql$conn);

    $row = mysql_fetch_assoc($rs);

    if(!empty($row)){

        echo $pad,'<br />';

        echo $row['content'],'<br />';

        mysql_query('update message set flag = 1');

    }

 

    ob_flush();

    flush();

    sleep(1);

}

 

同时在命令行中运行 mysql,插入数据:

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

C:\Users\Administrator>D:

 

D:\>cd wamp/bin/mysql/mysql5.5.20/bin

 

D:\wamp\bin\mysql\mysql5.5.20\bin>mysql -uroot -p

Enter password:

Welcome to the MySQL monitor.  Commands end with or \g.

Your MySQL connection id is 15

Server version: 5.5.20-log MySQL Community Server (GPL)

 

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> use msg

Database changed

mysql> insert into message values (1,'hello',0);

Query OK, 1 row affected (0.03 sec)

 

mysql> insert into message values (2,'world',0);

Query OK, 1 row affected (0.00 sec)

 

mysql>

 

此时页面的效果是:每插入一条数据,该数据就在页面中当即输出

  

该技术就叫 comet / server push / 反向 ajax 技术。

  

能够使用 Node.js(长链接)+Redis(队列服务器)+ PHP + comet(反向 ajax) 实现更好的即时聊天。

相关文章
相关标签/搜索