Skip to content

Instantly share code, notes, and snippets.

@aaronpk
Created October 13, 2013 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronpk/6958924 to your computer and use it in GitHub Desktop.
Save aaronpk/6958924 to your computer and use it in GitHub Desktop.
Sample code for real-time comments using http://indiewebcamp.com/webmention, Redis and Websockets.
var commentContainerSelector = '.references ul';
if($(commentContainerSelector).length > 0 && "WebSocket" in window) {
var ws = new WebSocket(window.location.origin.replace("http","ws")+":8077");
ws.onopen = function(event) {
// Send the current window URL to the server to register to receive notifications about this URL
ws.send(window.location);
};
ws.onmessage = function(event) {
// Whatever comes back from the websockets connection is rendered in the list
$(commentContainerSelector).append(event.data);
};
}
var WebSocketServer = require('ws').Server;
var Redis = require('redis');
var port = 8077;
var wss = new WebSocketServer({port: port});
wss.on('connection', function(ws) {
console.log("New websockets connection");
ws.on('message', function(message) {
var redis = Redis.createClient(6379, 'localhost');
var channel = 'replies::' + message;
redis.subscribe(channel);
// console.log('Listening for comments on channel ' + channel);
redis.on('message', function (channel, message) {
ws.send(message);
});
ws.on('close', function(){
// console.log('Killing listener for channel ' + channel);
redis.unsubscribe();
redis.end();
});
ws.on('error', function(){
// console.log('Killing listener for channel ' + channel);
redis.unsubscribe();
redis.end();
});
});
});
console.log("WebSocket Server Listening on port "+port);
<?php
/*
* When a new Webmention is received, broadcast the rendered HTML of the comment to any websocket listeners
*/
// ... Normal webmention processing code above
ob_start();
Site::displayComment($this->sourceURL); // Renders the comment HTML
$html = ob_get_clean();
redis()->publish('replies::' . $this->targetURL, $html);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment