views:

46

answers:

1

i made a chat using php and ajax, and i am using a while loop to check the database for new messages.

this is the code that retrieves the message:

//retrive message

function update(){

$(document).ready(function(){

$.ajax({

async: true,

type: "POST",

url: "listen.php",

success: function(data){

$("#myp").before(data);

},

complete: function(){

window.setTimeout("update();",100);
}

});

});

};


//wating for new message

<?php
include_once("connect.php");

$type="";

while($type!=='n'){


usleep(1000);

$search=mysql_query("SELECT * from chat ORDER BY id DESC LIMIT 1");

$row=mysql_fetch_assoc($search);

$type=$row['type'];

$id=$row['id'];

}

echo $row['message'] . "<br/>";


mysql_query("UPDATE chat SET type='o' WHERE id=$id");


?>

now this works fine,the php file constantly checks to see if there are any new messages, the update function starts when the page is loaded and waits for the response. but is it efficient? if i would use this on a website, im afraid it would stress the server too much, because of the while loop. does anyone know of a way, to make that while loop more server friendly?

A: 

Your hunch is correct. A typical server setup can answer any where between 100-1000 PHP requests per second, so doing 10 requests a second per client is going to eat up alot of resources on your server. While it might work create for a few people, it's not going to scale well. Your server might max out anywhere between 10-100 users (which is rather low).

One fix is to increase the time between each server poll, but this is only a linear fix and will degrade the experience of the users.

A better solution might be to use a comet approach. This is hard (if not impossible) to do purely with PHP, so you will need to deal with some external API to handle the long http requests.

Kendall Hopkins
thanks, but i dont understand what comet is exactly, where can i read more about it? because i dont know exactly what im looking for, so google doesnt really help.
Petre
@Petre Comet is when the client will connect to a server and listens until the server is ready to push data to client. This allows for a sort-of simulated "2-way" communication. Normally HTTP is one way (client -> server), but Comet allows for the server to push events to the client. This is rather hard to do w/ PHP since each connection requires a PHP process (which is very limiting due to ram overhead). This is why it probably better to look into a third party comet server. He's an example. http://github.com/mcarter/hookbox/tree/master/examples/php_simple_chat/
Kendall Hopkins