Last active
December 16, 2015 18:00
-
-
Save hidinginabunker/5474846 to your computer and use it in GitHub Desktop.
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 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 | |
}); | |
}); | |
}); | |
}); |
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
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/pharo/faa84d37912c211bc833