Skip to content

Instantly share code, notes, and snippets.

@hidinginabunker
Last active December 16, 2015 18:00
Show Gist options
  • Save hidinginabunker/5474846 to your computer and use it in GitHub Desktop.
Save hidinginabunker/5474846 to your computer and use it in GitHub Desktop.
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, Redis = require('redis')
, redis1 = Redis.createClient()
, redis2 = Redis.createClient()
;
redis1.on('error', function(err) {
console.log("Error "+err);
});
redis2.on('error', function(err) {
console.log("Error "+err);
});
app.listen(8000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
redis1.subscribe('client_votes');
redis1.on("message", function(channel, message) {
redis2.get('total_votes', function(err, total_votes) {
socket.emit('got_vote', {
votes: total_votes
});
});
});
socket.on('vote_up', function (data) {
redis2.incr('total_votes');
redis2.publish('client_votes', 'got_vote');
});
socket.on('get_votes', function(data) {
redis2.get('total_votes', function(err, total_votes) {
socket.emit('got_vote', {
votes: total_votes
});
});
});
});
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="styles/main.css">
<script src="/socket.io/socket.io.js"></script>
<!-- <script type="text/javascript" src="js/main.js"></script> -->
<title></title>
</head>
<body>
<h1>Voting</h1>
<span id="vote_count"></span>
<button id="vote_btn">Vote</button>
<script>
var socket = io.connect('http://localhost:8000');
var vote_count = document.getElementById("vote_count")
, vote_btn = document.getElementById("vote_btn")
socket.on('got_vote', function(data) {
console.log(data.votes);
vote_count.innerHTML = data.votes;
});
vote_btn.addEventListener('click', function() {
socket.emit('vote_up', {"vote": 1});
});
window.addEventListener('load', function() {
socket.emit('get_votes', {});
});
</script>
</body>
</html>
@jeremypharo
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment