php - best way to update chat room quickly, and reliably? -


i working on basic chatting service, school project, , going used amongst students. have been quite successful, have had 1 problem. updating chatroom. in many of tests tends use 10 seconds message received, , recognized user sent it.

it running php push messages chatfile , jquery load file. chat updated every 3 seconds. in tests chatfile gets updated instantly, actual chat not update fast, @ average of approximately 10 seconds.

i believe must limiation in jquery. should move away jquery , find better solution, or there code? appreciated. in advance!

there php in there too, load username , room name

jquery code:

    var roomname = "<?php echo $_get["room"]; ?>";     var prevdata = "";     update();     setinterval(function(){update()},3000)     $("#send").click(function(){         sendmessage();     });      $('#message').keyup(function(e){         if(e.keycode == 13)         {             sendmessage();         }     });      function update()     {         $.get("/rooms/room/"+roomname+".html",function(data){             $("#chatbox").html(data);             if(prevdata != data && data.indexof("<?php echo $_session["username"] ?>") != 31)             {             playmessagesound();             }             prevdata = data;         });     }      function sendmessage()     {         var message = $("#message").val();         $("#message").val("");         $.get("sendmessage.php?room="+roomname+"&message="+message)     }      function playmessagesound()     {         var audio = new audio("/sound/msg.mp3");         audio.play();     } 

my solution: took jwatts' solution , customised bit make in fewer lines of code. compare chat, file, , return differences, appending chat, making fast update can go!

thanks guys!

i know question has been answered, wanted throw in possible solution. is, these things go, simple 1 catches , caveats, class project suffice. example proposing not 1 have created myself, , code untested. , take fair bit of time implement changes , them work.

but explores basic data formats such xml , json capabilities in php , javascript. keeps track of recent data grab , gets new chat information. way once data gets browser, it's loading new stuff instead of whole thing.

in code above, looks writing entire chat, each time. sure there browser caching issue going on. rather requesting entire html page each time, request php returns json data (php has built-in json functions) includes last entries, , append document.

there lot of information available on json. if haven't learned yet, way of expressing data native javascript. can natively convert json formatted text arrays, objects, , properties. , not verbose xml.

in code, create time stamp called

var lastdatareceived = ""; 

this keep time stamp of last time new chat data received server. in $.get() success function, change url php page , set json data. also, pass in needed information such name of room need data from, , last time chat data received:

function update() {     $.get({         url: "/rooms/room/getchatdata.php",         data: { "room": roomname, "lastdatareceived": lastdatareceived },          success: function(data){             //..............         },         datatype: "json"     }); } 

this create request

"/rooms/room/chatdata.php?room="+roomname+"&lastdatareceived="+lastdatareceived  

on server side, can querystring parameters so

$roomname = $_get["room"]; $lastdatareceived = date_create_from_format('d/m/y h:i:s', $_get["lastdatareceived"]); 

it looks writing chat information html file. in example, using xml data preferable. there many, many php xml tutorials out there. here 1 @ w3schools.com simplexml functions. (http://www.w3schools.com/php/php_ref_simplexml.asp)

with can load file:

$xml = simplexml_load_file($roomname.".xml"); 

you can create new xml file if new room example:

<?php     $chats = <<<xml         <chats>         </chats>         xml;      $xml = new simplexmlelement($chats);     $xml->savexml($roomname.".xml"); ?> 

to determine whether read or write, can check if room exists checking if file room exists:

$xml = null; if (file_exists($roomname.".xml")) {     //set exsiting     $xml = simplexml_load_file($roomname.".xml"); } else {     //create new file        $chats = <<<xml         <chats>         </chats>         xml;     $xml = new simplexmlelement($chats);     $xml->savexml($roomname.".xml"); } 

either way $xml variable can work with.

so now, you've made request server see if there new chat data. you're working variables $roomname , $lastdatareceived created earlier. , you've loaded $xml object file. need find new additions.

$chats = $xml->chats->children(); $newchats = array();  foreach($chats $c) {     if ($c['date'] > $lastdatareceived) {         array_push($newchats, $c);     } } 

now have array of new chat items, write json data browser:

$json = json_encode($newchats); header('content-type: application/json'); echo $json; 

now javascript. in php sample above, $newchats initialized new array. when json_encode() called on it, if there no new chats, echo return empty array. can test in js.

in case, adding new items came in. need add new html document. super easy jquery. chats in <div> tag:

<div id="chats">     <!--all chats here--> </div> 

and have template div want chats like

<div class="chat_template" style="display:none;">     <div class="person_name"></div>     <div class="chat_text"></div>     <div class="chat_time"></div> </div> 

you can clone it, load data it, , append document.

function update() {     $.get({         url: "/rooms/room/chatdata.php",         data: { "room": roomname, "lastdatareceived": lastdatareceived },          success: function(data){             if (data.length > 0) {                 (var = 0; < data.length; i++) {[                     var c = data[i];                     //i not know exact structure of data be.                     // may need output data console see it's structure.                     // assuming have access date value, person's name                     // , text.                      //clone template , add values                     var div = $("div.chat_template").clone(true);                     div.find("div.person_name").html(name);                     div.find("div.chat_text").html(text);                     div.find("div.chat_time").html(date_val);                     div.show();                      //add new div document                     $("div#chats").append(div);                      //set last received time next query                     lastdatareceived = date_val;                 }                  playmessagesound();             }         },         datatype: "json"     }); } 

when sending new chat info server, can use same data: { "chattext": text....} type structure in jquery $.post() function. need different php file on server addchatdata.php. touched on algorithm gets or creates chat room file based on whether exists.

so if want child xml element this

<chat date="04/jun/2015 13:18:23" name="george">     here of george's text. </chat> 

once $xml object, can add new xml so:

$chat = $xml->addchild("chat", "here of george's text."); $chat->addattribute("date", date('d/m/y h:i:s')); $chat->addattribute("name", "george"); //<--or use variable name name  //then save changes out file: $xml->savexml($roomname.".xml"); 

in general sense, doing doing: storing data new chats, loading data other clients connected chat. however, here retrieving new information, , load faster on browser.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -