php - 如何使用 Jquery/PHP 实现聊天室?

标签 php javascript jquery ajax ajax-polling

我希望使用 PHP/Javascript (Jquery) 实现一个聊天室,同时具有群聊和私有(private)聊天功能。

问题在于如何以自然的方式不断更新界面,以及如何在私有(private)聊天中显示“X 正在输入..”消息。

显而易见的方法似乎是每 X 秒/毫秒 javascript 对服务器执行一次 ping 操作,并获取上次 ping 到现在之间的新消息列表。但是,如果聊天室突然充斥着 5 条消息,这会使界面看起来有点不自然。我希望每条消息都按键入时显示。

有没有办法让 javascript 保持与服务器的持续连接,服务器将任何新消息推送到此连接,然后 javascript 将它们添加到界面中,以便它们同时出现,几乎在服务器接收到它们的同时出现?

我知道有一些轮询选项需要您安装一些 apache 模块等,但我对系统管理员很差劲,因此我希望在共享主机帐户上有一个非常容易安装的解决方案,或仅 php/mysql 的解决方案。

最佳答案

使用 PHP/AJAX/JSON 聊天

我用这本书/教程编写了我的聊天应用程序:

AJAX and PHP: Building Responsive Web Applications: Chapter 5: AJAX chat and JSON .

它展示了如何从头开始编写完整的聊天脚本。


基于 Comet 的聊天

您还可以使用 CometPHP .

发件人:zeitoun :

Comet 使 Web 服务器能够向客户端发送数据,而无需客户端请求它。因此,这种技术将产生比经典 AJAX 响应更快的应用程序。在经典的 AJAX 应用程序中,无法实时通知 Web 浏览器(客户端)服务器数据模型已更改。用户必须创建一个请求(例如通过单击链接)或必须发生定期 AJAX 请求才能从服务器获取新数据。

我将向您展示两种使用 PHP 实现 Comet 的方法。例如:

  1. 基于隐藏<iframe>使用服务器时间戳
  2. 基于经典的 AJAX 非返回请求

第一个在客户端实时显示服务器日期,然后显示一个迷你聊天。

方法一:iframe + 服务器时间戳

你需要:

  • 用于处理持久性 http 请求的后端 PHP 脚本 backend.php
  • 前端 HTML 脚本加载 Javascript 代码 index.html
  • prototype JS library , 但你也可以使用 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>

前端脚本 ( index.html ) 创建一个“ cometd ”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>

方法二:AJAX不返回请求

您需要与方法 1 中相同的内容 + 用于数据交换的文件 (data.txt)

现在,backend.php 将做两件事:

  1. 发送新消息时写入“data.txt”
  2. 只要“data.txt”文件不变就无限循环
<?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> tags hat 将包含来自“data.txt”文件的聊天消息,最后它创建一个“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) {
      // 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>

或者

您还可以查看其他聊天应用程序,了解它们是如何做到的:

关于php - 如何使用 Jquery/PHP 实现聊天室?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174521/

相关文章:

php - 多个提交按钮 php 不同的操作

php - 如何确定 CodeIgniter 的速度?

php - 将页面重定向到根目录,但保留 URL 中的参数

javascript - 插件的 Npm 依赖项

php - 在网站上显示一个简单的条形图,没什么花哨的

javascript - document.head.appendChild(element) 即 ie7 和 ie8

javascript - 在不使用 css grid 和 css flex 的情况下创建类似的东西

javascript - 通过包含的字符串查找对象

javascript - 为什么启用和禁用按钮不起作用?

javascript - 将以下jQuery代码转换为纯Javascript