Server-Sent Events with libSSE - System load chart

libSSE can be used to send data regularly to the client such as syncing data from client to server.

In this example, the server sends back the system load every 5 seconds and display the data on a chart.

Source

  1. <?php
  2. require_once('../../src/libsse.php');
  3.  
  4. //This function fixes those who are in windows
  5. function get_server_load() {
  6.                 if (stristr(PHP_OS, 'win')) {
  7.                         $wmi = new COM("Winmgmts://");
  8.                         $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor");
  9.                         $cpu_num = 0;
  10.                         $load_total = 0;
  11.                         foreach($server as $cpu){
  12.                                 $cpu_num++;
  13.                                 $load_total += $cpu->loadpercentage;
  14.                         }
  15.                         $load = round($load_total/$cpu_num);
  16.         } else {
  17.                         $sys_load = sys_getloadavg();
  18.                         $load = $sys_load[0];
  19.                 }    
  20.         return (int) $load;
  21. }
  22.  
  23. class SysEvent extends SSETimedEvent { //Beware: use SSETimedEvent for sending data at a regular interval
  24.         public $period = 5;//the interval in seconds
  25.         public function update(){
  26.                 return json_encode(array('load'=>get_server_load(),'time'=>time()));
  27.         }
  28. }
  29.  
  30. $sse = new SSE();
  31. $sse->addEventListener('data',new SysEvent());
  32. $sse->start();
  33. ?>