Created
February 21, 2017 00:03
-
-
Save jacksonfdam/fc717a7cb99ae1aca7858d0145b81a48 to your computer and use it in GitHub Desktop.
Votação
This file contains hidden or 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
<!-- index.html --> | |
<html> | |
<head> | |
<title>Votacao Real-time</title> | |
<script src="/socket.io/socket.io.js"></script> | |
<script> | |
var socket = io.connect('http://localhost:5000'); | |
socket.on('toClient', function (votacao) { | |
console.log(votacao); | |
//var votos = JSON.parse(votacao); | |
document.getElementById('total_sim').innerHTML = votacao.sim; | |
document.getElementById('total_nao').innerHTML = votacao.nao; | |
}); | |
var votar = function(voto){ | |
socket.emit('votar', {voto: voto}); | |
}; | |
</script> | |
</head> | |
<body> | |
<h1>Votacao Real-time</h1> | |
<button onClick="votar('sim')">Sim</button> | |
<button onClick="votar('nao')">Nao</button> | |
<h2>SIM</h2> | |
<div id="total_sim">00</div> | |
<h2>NAO</h2> | |
<div id="total_nao">00</div> | |
</body> | |
</html> |
This file contains hidden or 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
// É necessário instanciar os módulos abaixo nessa ordem! | |
var app = require('express')(), | |
server = require('http').createServer(app), | |
io = require('socket.io').listen(server); | |
var cSim = 0, cNao = 0; | |
server.listen(5000, function() { | |
console.log("Votacao real-time..."); | |
}); | |
app.get('/', function(req, res) { | |
res.sendFile(__dirname + '/index.html'); | |
}); | |
// Eventos do Socket.IO | |
io.sockets.on('connection', function(socket) { | |
socket.on('votar', function(data) { | |
var msg = data.voto; | |
if (msg === 'sim') { | |
cSim += 1; | |
} else if (msg === 'nao') { | |
cNao += 1; | |
} else if (msg === 'zerar') { | |
cSim = 0; | |
cNao = 0; | |
} | |
var html = { sim : cSim, nao : cNao}; | |
socket.emit('toClient', html); | |
socket.broadcast.emit('toClient', html); | |
}); | |
}); |
This file contains hidden or 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
{ | |
"name": "aula-03", | |
"version": "0.0.2", | |
"description": "Exemplo da Aula 03", | |
"dependencies": { | |
"express": "^4.14.1", | |
"socket.io": "*" | |
}, | |
"engine": "node 0.6.x" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment