I'm developing a web app where a user can request a service and a provider will be available to respond to him. So, When a user requests for some sort of service, our application will send a notification to the provider (asking him to respond to the user). What I'm trying to do is: when a user requests a service, the provider gets the notification instantly (something like Facebook does).
One way to get this is using AJAX to send requests to the server every 5-10 secs; what we call is polling (so far I know). But, this method has some defects, I see:-
So, I wanted to know if there is some technique where we can update our web page instantly when a change occurs in our system without polling requests using AJAX.
here is a simple Server Sent Event Script using php.
support
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
js
var sse=new EventSource("sse.php");
sse.onmessage=function(e){
document.body.innerHTML=e.data;
};
sse.php
header('Content-Type: text/event-stream'); // specific sse mimetype
header('Cache-Control: no-cache'); // no cache
while(true) {
if(/*something changes*/){
echo "id: ".time().PHP_EOL;
echo "data: ".$data.PHP_EOL;
echo PHP_EOL;
}
ob_flush(); // clear memory
flush(); // clear memory
sleep(10);// seconds
}
this keeps the connection open with the client,
then it checks if something is changed ... db/file whatever
outputs the data if changed
and then clears the php cache
waits 10 seconds and does it again.
As you can see the client recieves the data only if something changes on the server
but i totally don't know how the server could handle 1000's of people.
node.js would be a better way. but it depends what languages you are using and/or if you can actually use node.js.
websockets is both ways.
server sent event is oneway.(you need this)
EDIT
more data inside the sse response:
js
var sse=new EventSource("sse.php");
sse.onmessage=function(e){
console.log(JSON.parse(e.data))
};
sse.php
header('Content-Type: text/event-stream'); // specific sse mimetype
header('Cache-Control: no-cache'); // no cache
while(true) {
if(/*something changes*/){
echo "id: ".time().PHP_EOL;
$dataArray=array('id'=>$id,'name'=>$name,'more'=>$more);
echo "data: ".json_encode($dataArray).PHP_EOL;
echo PHP_EOL;
}
ob_flush(); // clear memory
flush(); // clear memory
sleep(10);// seconds
}
if you need some more info just ask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With