Request to Apache server in chat app

360 Views Asked by At

I'm writing a chat application for joomla (apache server) and use this construction to emulate long-polling (server side):

function get_messages($last_id) {
   $time = time();
   while((time() - $time) < 25) {       
      $sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
      $db->setQuery($sql);
      $rows = $db->loadAssocList();
      if (count($rows)>0) { 
         echo 'JSON STRING HERE';  
      } else {
     flush();
  } 
   usleep(5000000);       
   }
}

How Can I optimize this part of code. Should I use infinite looping or should I avoid while construction? P/S: I know Apache is not best choice to write chat app for and node.js is better.

Thanks!

2

There are 2 best solutions below

2
On

Infinite loops are never a good idea because they hammer your server resources. You are better off having JS providing the intermittent polling to your get_messages function. Use a timeout and embed the script on any page that shows the messages.

0
On

I'm going to answer based on the limited information I've got to help you in the broadest way possible following industry standards. You need to not code in the way you currently are because it is very inefficient and quite frankly dangerous.

Here is the mootools code required to run an intervaled polling (I've used Mootools as you said you're using Joomla, I've assumed you're using 1.6+ as 1.5 is EOL this month):

//this sets how often you want to update (in milliseconds).
setInterval('chatPoll()',2000);
//this function essentially just grabs the raw data
//from the specified url and dumps it into the specified div
function chatPoll()
{
   var unixTimestamp Math.round(new Date().getTime() / 1000)
   var req = new Request({
      method: 'get',
      url: $('ajax-alert').get('http://www.yoururltoupdate.com/file.php?last=' + (unixTimestamp-2),
      data: { 'do' : '1' },
      onComplete: function(response) { response.inject($('my-chat-wrapper')); }
   }).send();
}

Your PHP file should look something look like this:

get_messages($_GET['last']);
function get_messages($last_id) {

      $sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
      $db->setQuery($sql);
      $rows = $db->loadAssocList();
      if (count($rows)>0) { 
         echo json_encode($rows);
      }     
}

I haven't fully tested this code but it should work and if not will definitely help answer your query as to how what you're trying to do should be achieved rather than the way you originally posted. If you really wanted to get fancy you could check out node.js as well. There is also tons of extensions for Joomla which work as chat mediums for support purposes if that's what you were after.