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

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

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

原理:一般而言,HTTP 协议的特点是,连接之后断开连接(服务器响应 Content-Length,收到了指定 Length 长度的内容时,也就断开了)。在 HTTP 1.1 协议中,允许不写 Content-Length,比如要发送的内容长度确实不知道,此时需要一个特殊的 Content-Type:chunked,叫做分块传输,只有当服务器最后发送 0 ,在表明服务器和客户端的此次连接彻底结束。

【例】

<?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:

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: 

<?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,插入数据:

C:UsersAdministrator>D:

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

D:wampinmysqlmysql5.5.20in>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) 实现更好的即时聊天。

参考:http://www.zixue.it/thread-15089-1-1.html

原文地址:https://www.cnblogs.com/dee0912/p/4660276.html