3

チャットプログラムを作成しています。このチャット プログラムには 2 つの側面 (クライアントとユーザー) があります。すべてのデータはデータベース (mysql) に入ります。現在、チャットは正常に機能しています。各サイド タイプと i には、ajax を使用してデータベース ファイルを 1 秒または 2 秒ごとにウィンドウにロードするリスナー関数があります。

問題は、これが帯域幅を使いすぎていることです!

一定時間後にチャットを終了することを考えていた、またはイベントが発生したときにのみ更新する方法があると考えていました。

私の意見では、理想的にはこれが最もうまくいくでしょう:

ユーザーが新しいデータを入力すると、それがクライアント側で検出され、その時点でのみチャット ウィンドウを更新する機能がアクティブになります。

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 に答える