-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (46 loc) · 1.4 KB
/
server.js
File metadata and controls
62 lines (46 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const http = require('http');
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/', function (req, res){
res.sendFile(__dirname + '/public/index.html');
});
var port = process.env.PORT || 3000;
var server = http.createServer(app)
.listen(port, function () {
console.log('Listening on port ' + port + '.');
});
var votes = {};
function countVotes(votes) {
var voteCount = {
A: 0,
B: 0,
C: 0,
D: 0
};
for (var vote in votes) {
voteCount[votes[vote]]++
}
return voteCount;
}
const socketIo = require('socket.io');
const io = socketIo(server);
io.on('connection', function (socket) {
console.log('A user has connected.', io.engine.clientsCount);
io.sockets.emit('userConnection', io.engine.clientsCount);
socket.emit('statusMessage', 'You have connected.');
socket.on('message', function (channel, message) {
if (channel === 'voteCast') {
votes[socket.id] = message;
socket.emit('voteCount', countVotes(votes));
socket.emit('yourVote', message);
}
});
socket.on('disconnect', function () {
console.log('A user has disconnected.', io.engine.clientsCount);
delete votes[socket.id];
socket.emit('voteCount', countVotes(votes));
io.sockets.emit('userConnection', io.engine.clientsCount);
});
});
module.exports = server;