Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created November 20, 2012 19:13
Show Gist options
  • Save gavinblair/4120334 to your computer and use it in GitHub Desktop.
Save gavinblair/4120334 to your computer and use it in GitHub Desktop.
Simple Server Sent Events Example
<?php
header('Cache-Control: no-cache');
header('Content-Type: text/event-stream');
$data = '';
// do stuff, get $something
$result = db_query('SELECT COUNT(*) as count FROM users WHERE last_login > date_add(current_timestamp, interval -15 minute)');
$usercount = db_fetch_array($result)[0]->count;
echo "count: " . $usercount . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
exit();
var source = new EventSource("eventstream.php");
var current;
source.onmessage = function(event){
if(event.data && event.data != current){
current = event.count;
//data has changed, do stuff!
$("#users-online").text(current);
}
}
<html>
<head>
<title>Number of users</title>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div id="users-online">0</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment