Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Forked from louisremi/client.js
Created June 16, 2011 14:03
Show Gist options
  • Save rwaldron/1029280 to your computer and use it in GitHub Desktop.
Save rwaldron/1029280 to your computer and use it in GitHub Desktop.
Friends Timeline snippets
// Create an EventSource object,
// passing it the URL of the server sccript
var evtSrc = new EventSource( "server.php" ),
// Setup event types, provide explicit values if nec.
eventTypes = {
message: "status",
checkin: 1,
forward: 1,
direct: 1
};
// Create listeners for each event type
[].forEach.call( Object.keys( eventTypes ), function( type ) {
var eventType = eventTypes[ type ],
// determine if the className should be overridden by explicit value
className = eventType === 1 ? eventType : type;
evtSrc.addEventListener( type, function( e ) {
addMessage( className, JSON.parse(e.data) );
}, false);
});
// Parse the data and insert the message in the timeline
// with the appropriate className
function addMessage( className, data ) {
//console.log( className, data );
}
data: {"from": "Sandrine", "msg": "dressed in blue today", "location":"Brussel"}
event: direct
data: {"from": "yann", "msg": "You should check your inbox", "location": "Boston"}
event: checkin
data: {"from": "Peter", "place": "StarCoffee", "location": "Berlin"}
event: forward
data: {"from": "roland", "through": "Sasha", "msg": "watch this! http://youtu.be/LybAHotsvOg", "location": "Mexico"}
<?php
// Send appropriate mime type
header("Content-Type: text/event-stream\n\n");
// Read messages
$filename = "messages.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
// Split the messages into an array
$messages = preg_split( "/\n\n/", $contents );
// Send one message every 2 to 7 seconds
foreach ( $messages as $message ) {
echo $message;
echo "\n\n";
ob_flush();
flush();
sleep( rand(2, 7) );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment