Frage

I have implemented a chat system using comet technique. Here is the link (see 2nd method with ajax) comet with ajax

I am using it with 2 browsers and with 2 accounts when i send message with one account, the other receiver receives it with its own name. Here is the code:

handleResponse: function(response)
{

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

},

here s controller

$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();

Suppose if i type xyz: helo world! then in 2nd browser i receive this message as abc: helo world! abc and xyz are 2 users. What is the problem in the code? I can't understand. thanks..

War es hilfreich?

Lösung 2

You use the session data of the current user as the name but the sender actually isn't the current user. Perhaps you can send the username and the message together to the server?

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

Update

Although this is a little bit late, you can encode your data into JSON. Then, when you use it, you can decode it.

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

When you write message to the file, you can use this:

<?php
file_put_contents($filename,json_encode(array('msg'=>$msg,'name'=>$name)));

Andere Tipps

you should use this hope will work

     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.

thanks to nostrzak

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top