3

我正在创建一个聊天程序。这个聊天程序有两个方面(客户端和用户)。所有数据都进入数据库(mysql)。目前,聊天工作正常。每一面类型,我都有一个侦听器函数,它使用 ajax 每秒或每两秒钟将数据库文件加载到窗口中。

问题是,这占用了太多带宽!

我正在考虑在设定的持续时间后终止聊天,或者我在想有一种方法可以仅在事件发生时更新。

理想情况下,这在我看来效果最好:

如果用户输入了新数据,那么客户端会检测到它,然后它会激活仅在那个时候更新聊天窗口的功能。

在 ajax/jquery/javascript 中是否存在这样的东西来监听?

这是我目前用来收听的代码:

/* set interval of listener */ 

 setInterval(function() {
listen()
}, 2500);

 /* actual listener */

 function listen(){
    /* send listen via post ajax */
    $.post("listenuser.php", {
        chatsession: $('#chatsession').val(),       
/* Do some other things after response and then update the chat window with response content from database window */
    }, function(response){
        $('#loadingchat').hide();
         $('#chatcontent').show();
        $('#messagewindow').show();
        setTimeout("finishAjax('messagewindow', '"+escape(response)+"')", 450);
    });
    return false; 
}
4

1 回答 1

2

有很多方法可以做到这一点,但看看你的设计,我建议使用一种称为 Comet 的技术,基本上是一种让 Web 服务器“发送”数据到客户端而无需客户端请求它的方法。根据我的观点,如果您阅读代码,那是一种黑客行为。但这里有一个例子,我发现如何使用一个简单的文本文件来实现这个:

服务器

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

我希望它有所帮助。

这是一个包含更多示例和一些文档的 URL(我从这里获得了示例): http ://www.zeitoun.net/articles/comet_and_php/start

于 2012-12-09T04:23:30.883 回答