I am trying to build a MySQL, PHP, Ajax based personal messaging system.
There is one table for all messages - msghistory
, which looks like that
And another one for users' last message check date records - chkdate
.
The system works like this:
When user signs into page, page fires Ajax autocheck. Ajax calls php in every 10 sec. PHP side checks for new messages by user id. At first checks chkdate
, then checks msghistory
: If there are no message after last check date then system will not notify user, else will notify about this
I think this way will load server heavily, if there are 1000s of users. I wonder if explained above way is optimal? if not, what do you think about this, which way is better?
Long polling is a good idea. Here's approximately how it works (though you can vary the lengths of time used). Have your PHP script (the one the client requests) run a (semi-)infinite loop that checks for a new message in the database. If no message is found, use the sleep() function to wait for ten seconds or so before the loop goes through again. Once a message is found, send it out to the client and break out of the loop. The client can then display the message, then start a new request to the "long polling" PHP script, another ten seconds later.
Here is a demo PHP script: $username=$_GET["username"];
<?php
while(1) {
$messages=mysql_query("SELECT * FROM `msghistory` WHERE `to_id`='$username'");
if (!mysql_num_rows($messages) === 0) {
//do whatever message processing and printout you need to do here
break;//break out of the loop. the script terminates and returns its messages to the client
}
}
?>
In the near future, we are going to see the implementation of WebSockets, which allow for real-time, push-pull communication between client and server. In many cases, though, this technology is not yet ready for use. Until then, long polling is the way to go.