Scenario
To deliver instant notifications to the client, I'm sending an AJAX request to a PHP page that checks if there are new notifications: if there are, it outputs them, otherwise it sleeps for 10 seconds before trying again, so it has a basic structure similar to the following one.
<?php
$max_attempts = 10000;
for($i=0;$i<=$max_attempts;$i++){
check_new_notifications(); //checking notifications in an sql database
if(new_notification){
echo $notification;
break;
}
else{
sleep(10);
}
}
?>
What is missing
While this is great for the client, as it doesn't have to send a request every 10 seconds, but just one, I can't find a better way for the server than to check every 10 seconds if there are new notifications.
My question
What solution could I adopt in order to avoid the server to constantly check for new notifications?
-
1Turn the problem on its head--use something like SignalR to push notifications down to waiting clients.mgw854– mgw8542015年07月29日 17:49:35 +00:00Commented Jul 29, 2015 at 17:49
1 Answer 1
You can:
Use polling
However, think about sending a request every 10 seconds.
By using your suggested approach, you are keeping a long connection to the server, which is in turn keeping a busy process/thread.
If this is used only by you, it's fine.
If it's meant to be used by many users, it's a huge waste of resources, since the server will be busy doing nothing 99% of the time.
Use Websockets
This is the thing you need.
Websockets provide a direct and continous TCP communication between the browser and your server. Check out Ratchet, that's a great PHP library for websockets on the server side.
Use an external service
There are services like Pusher which also utilize websockets. However, you don't need a socket server yourself, but send them an event from your backend. Then their service pushes new data to your browser.
Explore related questions
See similar questions with these tags.