Cli*_*ote 25 javascript php ajax jquery ajax-polling
我正在寻找使用PHP/Javascript(Jquery)实现聊天室,同时具有群聊和私聊功能.
问题是如何以自然的方式不断更新界面,以及如何在私人聊天中显示"X正在输入..."消息.
显而易见的方式似乎是每隔x秒/毫秒javascript ping服务器并在最后一次ping和现在之间获取新消息列表.然而,这可能会使界面看起来有点不自然,如果突然聊天室充斥着5条消息.我希望每条消息都会在输入时显示.
有没有办法使javascript保持与服务器的连续连接,服务器将任何新消息推送到此连接,并且javascript将它们添加到接口,以便它们同时出现,几乎在服务器收到它们之后?
我知道有一些轮询选项需要你安装一些apache模块等,但我很糟糕的系统管理员,因此我更喜欢在共享主机帐户或php上有一个非常容易安装的解决方案/ mysql唯一的解决方案.
Wou*_*elo 46
我用这本书/教程写了我的聊天应用程序:
AJAX和PHP:构建响应式Web应用程序:第5章:AJAX聊天和JSON.
它展示了如何从头开始编写完整的聊天脚本.
来自:zeitoun:
Comet使Web服务器能够将数据发送到客户端,而无需客户端请求它.因此,这种技术将产生比传统AJAX更具响应性的应用程序.在传统的AJAX应用程序中,无法实时通知Web浏览器(客户端)服务器数据模型已更改.用户必须创建请求(例如通过单击链接)或定期的AJAX请求必须发生才能从服务器获取新数据.
我将向您展示使用PHP实现Comet的两种方法.例如:
<iframe>使用服务器时间戳第一个在客户端上实时显示服务器日期,显示迷你聊天.
你需要:
backend.phpindex.html后端脚本(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">
// KHTML browser don't share javascripts between iframes
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);
}
// load the comet object
var comet = window.parent.comet;
</script>
<?php
while(1) {
echo '<script type="text/javascript">';
echo 'comet.printServerTime('.time().');';
echo '</script>';
flush(); // used to send the echoed data to the client
sleep(1); // a little break to unload the server CPU
}
?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
前端脚本(index.html)创建一个"彗星"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) {
// For IE browsers
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) {
// for KHTML browsers
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 {
// For other browser (Firefox...)
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);
}
},
// this function will be called from backend.php
printServerTime: function (time) {
$('content').innerHTML = time;
},
onUnload: function() {
if (comet.connection) {
comet.connection = false; // release the iframe to prevent problems with IE when reloading the page
}
}
}
Event.observe(window, "load", comet.initialize);
Event.observe(window, "unload", comet.onUnload);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
你需要与方法1相同+一个dataexchange文件(data.txt)
现在,backend.php将做两件事:
Run Code Online (Sandbox Code Playgroud)<?php $filename = dirname(__FILE__).'/data.txt'; // store new message in the file $msg = isset($_GET['msg']) ? $_GET['msg'] : ''; if ($msg != '') { file_put_contents($filename,$msg); die(); } // infinite loop until the data file is not modified $lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0; $currentmodif = filemtime($filename); while ($currentmodif <= $lastmodif) // check if the data file has been modified { usleep(10000); // sleep 10ms to unload the CPU clearstatcache(); $currentmodif = filemtime($filename); } // return a json array $response = array(); $response['msg'] = file_get_contents($filename); $response['timestamp'] = $currentmodif; echo json_encode($response); flush(); ?>
前端脚本(index.html)创建<div id="content"></div>标签帽子将包含来自"data.txt"文件的聊天消息,最后它创建一个"彗星"javascript对象,它将调用后端脚本以便观察新的聊天消息.
每次收到新消息时以及每次发布新消息时,comet对象都将发送AJAX请求.持久连接仅用于监视新消息.timestamp 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) {
// handle the server response
var response = transport.responseText.evalJSON();
this.comet.timestamp = response['timestamp'];
this.comet.handleResponse(response);
this.comet.noerror = true;
},
onComplete: function(transport) {
// send a new ajax request when this request is finished
if (!this.comet.noerror)
// if a connection problem occurs, try to reconnect each 5 seconds
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>
Run Code Online (Sandbox Code Playgroud)
您还可以查看其他聊天应用程序,了解他们是如何做到的:
http://hot-things.net/?q=blite - BlaB!Lite是基于AJAX的,可以通过任何支持MySQL,SQLite和PostgreSQL数据库的浏览器聊天系统获得最佳浏览效果.
Gmail/Facebook风格jQuery聊天 - 这个jQuery聊天模块使您可以将Gmail/Facebook风格的聊天无缝集成到现有网站中.
CometChat - CometChat在标准共享服务器上运行.只需要PHP + mySQL.
轮询不是一个好主意.您需要一个使用长轮询或Web套接字的解决方案.
http://hookbox.org可能是您可以使用的最佳工具.
它是一个存在于服务器和浏览器之间的盒子,管理称为通道的抽象(想想IRC通道).它是github上的开源:https://github.com/hookbox/hookbox该框是用Python编写的,但它可以很容易地与任何语言编写的服务器一起使用.它还带有一个基于jsio构建的Javascript库(使用websockets,长轮询或浏览器上可用的最佳技术),保证它使用浏览器中提供的最佳技术.在演示中我看到了用几行代码实现实时聊天.
Hookbox的目的是简化实时Web应用程序的开发,重点是与现有Web技术的紧密集成.简而言之,Hookbox是一个支持Web的消息队列.浏览器可以直接连接到Hookbox,订阅命名频道,以及在这些频道上实时发布和接收消息.外部应用程序(通常是Web应用程序本身)也可以通过Hookbox REST接口将消息发布到通道.所有身份验证和授权都由外部Web应用程序通过指定的"webhook"回调执行.

每当用户连接或操作频道时,(订阅,发布,取消订阅)Hookbox都会向Web应用程序发出http请求以授权该操作.订阅频道后,用户的浏览器将通过javascript api接收来自另一个浏览器的实时事件,或者通过REST api从Web应用程序接收.
他们的主要观点是,使用hookbox进行的所有应用程序开发都可以在javascript中运行,也可以在Web应用程序本身的本地语言中运行(例如PHP).
你需要一个可以运行Python的服务器,但你不必了解Python.
如果您只想使用websockets和PHP,这是一个很好的起点:http://blancer.com/tutorials/69066/start-using-html5-websockets-today/
| 归档时间: |
|
| 查看次数: |
30172 次 |
| 最近记录: |