Created
October 13, 2013 06:51
-
-
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.
This file contains 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 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); | |
}; | |
} |
This file contains 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 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); |
This file contains 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 | |
/* | |
* 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