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 appli
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