Created
November 20, 2012 19:13
-
-
Save gavinblair/4120334 to your computer and use it in GitHub Desktop.
Simple Server Sent Events Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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