使用PHP/AJAX/JSON进行聊天
我使用了这本书/教程来编写我的聊天应用:
AJAX和PHP:构建响应式Web应用程序:第5章:AJAX聊天和JSON。
它展示了如何从头开始编写完整的聊天脚本。
基于Comet的聊天
您也可以使用Comet与PHP。
来自:zeitoun:
Comet使Web服务器能够向客户端发送数据,而无需客户端请求。因此,这种技术将比经典的 AJAX 产生更加响应的应用程序。在经典的 AJAX 应用程序中,Web浏览器(客户端)无法实时通知服务器数据模型已更改。用户必须创建请求(例如,通过单击链接)或必须定期发生 AJAX 请求以获取来自服务器的新数据。
我将向您展示两种使用PHP实现Comet的方法。例如:
- 基于隐藏的
<iframe>
使用服务器时间戳
- 基于经典 AJAX 非返回请求
第一种方法在客户端上实时显示服务器日期,然后显示迷你聊天。
方法1:iframe + 服务器时间戳
您需要:
- 一个后端PHP脚本来处理持久的HTTP请求
backend.php
- 一个前端HTML脚本加载JavaScript代码
index.html
- 原型JS库,但您也可以使用jQuery
后端脚本(backend.php
)将执行无限循环,并在客户端连接时返回服务器时间。
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sun, 5 Mar 2012 05:00:00 GMT");
flush();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet php backend</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
var is_khtml = navigator.appName.match("Konqueror") || navigator.appVersion.match("KHTML");
if (is_khtml)
{
var prototypejs = document.createElement('script');
prototypejs.setAttribute('type','text/javascript');
prototypejs.setAttribute('src','prototype.js');
var head = document.getElementsByTagName('head');
head[0].appendChild(prototypejs);
}
var comet = window.parent.comet;
</script>
<?php
while(1) {
echo '<script type="text/javascript">';
echo 'comet.printServerTime('.time().');';
echo '</script>';
flush();
sleep(1);
}
?>
</body>
</html>
前端脚本(
index.html
)创建了一个名为“comet”的JavaScript对象,它将把后端脚本连接到时间容器标签。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<div id="content">The server time will be shown here</div>
<script type="text/javascript">
var comet = {
connection : false,
iframediv : false,
initialize: function() {
if (navigator.appVersion.indexOf("MSIE") != -1) {
comet.connection = new ActiveXObject("htmlfile");
comet.connection.open();
comet.connection.write("<html>");
comet.connection.write("<script>document.domain = '"+document.domain+"'");
comet.connection.write("</html>");
comet.connection.close();
comet.iframediv = comet.connection.createElement("div");
comet.connection.appendChild(comet.iframediv);
comet.connection.parentWindow.comet = comet;
comet.iframediv.innerHTML = "<iframe id='comet_iframe' src='./backend.php'></iframe>";
} else if (navigator.appVersion.indexOf("KHTML") != -1) {
comet.connection = document.createElement('iframe');
comet.connection.setAttribute('id', 'comet_iframe');
comet.connection.setAttribute('src', './backend.php');
with (comet.connection.style) {
position = "absolute";
left = top = "-100px";
height = width = "1px";
visibility = "hidden";
}
document.body.appendChild(comet.connection);
} else {
comet.connection = document.createElement('iframe');
comet.connection.setAttribute('id', 'comet_iframe');
with (comet.connection.style) {
left = top = "-100px";
height = width = "1px";
visibility = "hidden";
display = 'none';
}
comet.iframediv = document.createElement('iframe');
comet.iframediv.setAttribute('src', './backend.php');
comet.connection.appendChild(comet.iframediv);
document.body.appendChild(comet.connection);
}
},
printServerTime: function (time) {
$('content').innerHTML = time;
},
onUnload: function() {
if (comet.connection) {
comet.connection = false;
}
}
}
Event.observe(window, "load", comet.initialize);
Event.observe(window, "unload", comet.onUnload);
</script>
</body>
</html>
方法2:AJAX非返回请求
您需要与方法1相同的内容+用于数据交换的文件(data.txt
)
现在,backend.php将执行两件事:
- 当有新消息发送时,写入“data.txt”
- 只要“data.txt”文件未更改,就会执行无限循环
<?php
$filename = dirname(__FILE__).'/data.txt';
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
file_put_contents($filename,$msg);
die();
}
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif)
{
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
?>
前端脚本(
index.html
)创建包含来自"data.txt"文件的聊天消息的
<div id="content"></div>
标签,最后创建一个名为"comet"的javascript对象,该对象将调用后端脚本以监视新的聊天消息。
每当接收到新消息并且每当发布新消息时,"comet"对象将发送AJAX请求。持久连接仅用于监视新消息。使用时间戳url参数来标识上次请求的消息,这样服务器将仅在"data.txt"时间戳更新时返回。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<div id="content">
</div>
<p>
<form action="" method="get" onsubmit="comet.doRequest($('word').value);$('word').value='';return false;">
<input type="text" name="word" id="word" value="" />
<input type="submit" name="submit" value="Send" />
</form>
</p>
<script type="text/javascript">
var Comet = Class.create();
Comet.prototype = {
timestamp: 0,
url: './backend.php',
noerror: true,
initialize: function() { },
connect: function()
{
this.ajax = new Ajax.Request(this.url, {
method: 'get',
parameters: { 'timestamp' : this.timestamp },
onSuccess: function(transport) {
var response = transport.responseText.evalJSON();
this.comet.timestamp = response['timestamp'];
this.comet.handleResponse(response);
this.comet.noerror = true;
},
onComplete: function(transport) {
if (!this.comet.noerror)
setTimeout(function(){ comet.connect() }, 5000);
else
this.comet.connect();
this.comet.noerror = false;
}
});
this.ajax.comet = this;
},
disconnect: function()
{
},
handleResponse: function(response)
{
$('content').innerHTML += '<div>' + response['msg'] + '</div>';
},
doRequest: function(request)
{
new Ajax.Request(this.url, {
method: 'get',
parameters: { 'msg' : request
});
}
}
var comet = new Comet();
comet.connect();
</script>
</body>
</html>
或者
你还可以看看其他聊天应用程序来了解它们是如何实现的:
PHP in CLI=Yes
,PHP in HTTP call=No
,PHP + Javascript=Possible cause JavaScript can fire multi requests
PHP在CLI中=是
,PHP在HTTP调用中=否
,PHP + Javascript=可能会导致JavaScript触发多个请求
- ajreal