-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (63 loc) · 2.15 KB
/
Copy pathserver.js
File metadata and controls
78 lines (63 loc) · 2.15 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const http = require('http');
const express = require('express');
const app = express();
// Keep track of votes in memory
var votes = {};
// Have Express serve the 'public' directory
app.use(express.static('public'));
// Set up routing for root path
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
// Tell server what port to listen on
const port = process.env.PORT || 3000;
// Produce a server by passing the app object to Node's http module
const server = http.createServer(app).listen(port, function() {
console.log('Lisening on port ' + port + '.');
});
// Host WebSocket connections on http server
const socketIo = require('socket.io');
const io = socketIo(server);
// Set up event listener for the 'connection' event on the server
io.on('connection', function(socket) {
console.log('A user has connected.');
console.log(io.engine.clientsCount + ' user(s) now connected.');
// Broadcast total connected user count to all users
io.sockets.emit('usersConnected', io.engine.clientsCount + ' user(s) now connected.');
// Send message to current client (one socket = one client)
socket.emit('statusMessage', 'You have connected.');
socket.on('disconnect', function() {
console.log('A user has disconnected.');
// Broadcast total connected user count to all users
io.sockets.emit('usersConnected', io.engine.clientsCount + ' user(s) now connected.');
// Delete vote when a user disconnects
delete votes[socket.id];
socket.emit('voteCount', countVotes(votes));
console.log('Votes: ', votes);
});
// Save vote to memory when one is cast
// Send vote count to each client
socket.on('message', function(channel, message) {
if (channel === 'voteCast') {
votes[socket.id] = message;
socket.emit('voteCount', countVotes(votes));
console.log('Votes: ', votes);
}
});
});
// TODO: Refactor using Lo-Dash
// Keep track of vote counts
function countVotes(votes) {
var voteCount = {
A: 0,
B: 0,
C: 0,
D: 0
};
for (vote in votes) {
voteCount[votes[vote]]++
}
return voteCount;
}
// Create public interface with npm's module system
module.exports = server;