Web Page update without polling

懵懂的女人 提交于 2019-11-30 10:31:17

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!