如何使用Jquery/PHP实现聊天室?
我希望使用PHP/Javascript(Jquery)实现一个聊天室,该聊天室同时具有群组聊天和私人聊天功能 问题在于如何以自然的方式不断更新界面,以及如何在私人聊天中显示“X正在键入…”消息 最明显的方式似乎是,javascript每隔X秒/毫秒对服务器进行ping,并从最后一次ping到现在获取一个新消息列表。然而,如果聊天室突然被5条消息淹没,这会使界面看起来有点不自然。我希望每封邮件都按输入的样子显示 javascript是否有办法保持与服务器的连续连接,服务器将任何新消息推送到该连接,javascript将它们添加到界面中,以便它们几乎在服务器接收到消息时同时出现如何使用Jquery/PHP实现聊天室?,php,javascript,jquery,ajax,ajax-polling,Php,Javascript,Jquery,Ajax,Ajax Polling,我希望使用PHP/Javascript(Jquery)实现一个聊天室,该聊天室同时具有群组聊天和私人聊天功能 问题在于如何以自然的方式不断更新界面,以及如何在私人聊天中显示“X正在键入…”消息 最明显的方式似乎是,javascript每隔X秒/毫秒对服务器进行ping,并从最后一次ping到现在获取一个新消息列表。然而,如果聊天室突然被5条消息淹没,这会使界面看起来有点不自然。我希望每封邮件都按输入的样子显示 javascript是否有办法保持与服务器的连续连接,服务器将任何新消息推送到该连接,
我知道有一些轮询选项需要您安装一些apache模块等,但我对系统管理员很差,因此我更希望在共享主机帐户上有一个非常易于安装的解决方案,或者只使用php/mysql的解决方案。我以前没有使用过php,但最好使用某种套接字连接。这是插座的配置
我不记得是谁的教程了,但我用Flash作为客户端,Java作为服务器,创建了一个你想要的聊天室。我想这可能就是本教程所在的地方,它可能会对您有所帮助。您有没有看过,它是使用libevent和pnctl编写的?有很多功能,甚至是简单的演示应用程序。甚至它也有一些生产实现。我建议您与我们一起尝试。IO为您提供了一个漂亮且非常简单的客户端API,可在大多数现代浏览器上运行,并尽可能使用适当的传输(Websocket、长轮询等)。NodeJS是一个服务器端守护程序,它保存HTTP连接。Socket.IO的官方网站包含如何将它们结合使用的信息。希望它能对您有所帮助。我相信您正在研究的问题需要使用comet web编程。你可以在wikipedia、Comet编程和Ajaxian上找到更多细节(我对这个网站还是新手,在回复中只能发布一个链接) 问题是,在服务器端使用php很难实现这一点。更多详情: 此外,如果你在谷歌上搜索“php comet”,你会找到一个教程来达到预期的效果 以后编辑 使用此引擎实现了一个项目。太好了 希望这有帮助,
加布里埃尔这可能是一个很好的起点 用PHP/AJAX/JSON聊天 我使用本书/教程编写聊天应用程序: 它展示了如何从头开始编写完整的聊天脚本
基于Comet的聊天 您还可以使用with 发件人:: Comet使web服务器能够向客户端发送数据,而无需客户端请求数据。因此,这种技术将产生比经典AJAX更具响应性的应用程序。在经典的AJAX应用程序中,无法实时通知web浏览器(客户端)服务器数据模型已更改。用户必须创建一个请求(例如通过单击链接),或者必须定期发出AJAX请求,以便从服务器获取新数据 我将向您展示用PHP实现Comet的两种方法。例如:
- 用于处理持久http请求的后端PHP脚本
backend.PHP
- fronded HTML脚本加载Javascript代码
index.HTML
- 可以使用jQuery,但也可以使用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">
// 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>
方法2:AJAX非返回请求
您需要与方法1中相同的数据交换文件(data.txt
)
现在,backend.php将做两件事:
或者 您还可以查看其他聊天应用程序,了解它们是如何做到这一点的:
- -废话!Lite是一个基于AJAX的浏览器聊天系统,最好使用支持MySQL、SQLite和PostgreSQL数据库的浏览器聊天系统进行查看
- -此jQuery聊天模块使您能够将Gmail/Facebook风格的聊天无缝集成到现有网站中
- -教程
- -CometChat在标准共享服务器上运行。只需要PHP+mySQL
有一个开源软件。轮询不是一个好主意。您需要使用长轮询或web套接字的解决方案 可能是你能使用的最好的工具 它是一个位于服务器和浏览器之间的盒子,管理称为通道的抽象(想想IRC通道)。它在github上是开源的:box是用Python编写的,但是可以轻松地与任何语言编写的服务器一起使用。它还附带了一个基于jsio的Javascript库(使用WebSocket、长轮询或浏览器上可用的任何最佳技术),以确保它使用浏览器中可用的最佳技术。在一个演示中,我看到了一个实时聊天,只需几行代码即可实现 Hookbox的目的是简化实时web应用程序的开发,重点是与现有web应用程序的紧密集成
<!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>
<?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();
?>
<!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>