0

コメットテクニックを使ったチャットシステムを実装しました。ここにリンクがあります(ajaxを使用した2番目の方法を参照)comet with ajax

私は2つのブラウザと2つのアカウントで使用しています.1つのアカウントでメッセージを送信すると、もう1つの受信者はそれを独自の名前で受信します. コードは次のとおりです。

handleResponse: function(response)
{

 $('chat_id_box').innerHTML += '<u class="myId">' + response['name'] + '</u>:&nbsp;&nbsp;<p class="talk">' + response['msg'] + '</p></br>';

},

こちらがコントローラー

$filename  = dirname(__FILE__).'./data.txt';
    $name   =   $this->session->userdata('name');
 // store new message in the file
  $msg = isset($_GET['msg']) ? $_GET['msg'] : '';
  if ($msg != '')
   {
  file_put_contents($filename,$msg.$name);
   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['name']         =   file_get_contents($filename);
  $response['timestamp'] = $currentmodif;
    echo json_encode($response);
  flush();

xyz: helo world!と入力するとします。 次に、2 番目のブラウザーで、このメッセージをabc: helo world!として受け取ります。 abcxyzは 2 人のユーザーです。コードの問題は何ですか?理解できません。ありがとう..

4

2 に答える 2

2

あなたはこの希望を使うべきです

     file_put_contents($filename, implode(';', array($msg, $name)));
     $response = explode(';', file_get_contents($filename));
     $response[0] is your msg and $response[1] is your name.

nostrzakのおかげで

于 2013-03-01T14:58:42.163 に答える
1

現在のユーザーのセッション データを名前として使用しますが、送信者は実際には現在のユーザーではありません。おそらく、ユーザー名とメッセージを一緒にサーバーに送信できますか?

handleResponse: function(response)
{
    $('chat_id_box').innerHTML += '<u class="myId">'+response.user+'</u>:&nbsp;&nbsp;<p class="talk">'+response.msg+'</p></br>';
}

アップデート

これは少し遅れていますが、データを JSON にエンコードできます。その後、使用するときにデコードできます。

<?php
$response = json_decode(file_get_contents($filename));
$response->timestamp = $currentmodif;
echo json_encode($response);
flush();

メッセージをファイルに書き込むときは、これを使用できます。

<?php
file_put_contents($filename,json_encode(array('msg'=>$msg,'name'=>$name)));
于 2013-03-01T12:04:16.390 に答える