PageRenderTime 43ms CodeModel.GetById 23ms app.highlight 13ms RepoModel.GetById 2ms app.codeStats 0ms

/routes/socket.js

https://github.com/carlgrundberg/pivoter-angular
JavaScript | 74 lines | 61 code | 13 blank | 0 comment | 6 complexity | 0dc3547dda6ca67ae5514c0fe14e584d MD5 | raw file
 1module.exports = function (io) {
 2
 3    var state = {
 4        voters: {},
 5        total: 0,
 6        voted: 0
 7    };
 8
 9    function total_voters() {
10        return Object.keys(state.voters).length;
11    }
12
13    function num_voted() {
14        var voted = 0;
15        for (var i in state.voters) {
16            if (state.voters[i] != null) {
17                voted++;
18            }
19        }
20        return voted;
21    }
22
23    function reset_state() {
24        for (var i in state.voters) {
25            state.voters[i] = null;
26        }
27    }
28
29    function vote(id, value) {
30        state.voters[id] = value;
31        send_update();
32    }
33
34    function send_update(socket) {
35        state.total = total_voters();
36        state.voted = num_voted();
37
38        if (socket) {
39            console.log('sending update to socket ' + socket.id);
40            socket.emit('update', state);
41        } else {
42            console.log('sending update to all');
43            io.sockets.emit('update', state);
44        }
45    }
46
47    io.sockets.on('connection', function (socket) {
48
49        var address = socket.handshake.address;
50        console.log("New connection from " + address.address + ":" + address.port + " (" + socket.handshake.headers.referer + ")");
51        send_update(socket);
52
53        socket.on('voter', function () {
54            console.log('New voter');
55            vote(socket.id, null);
56        });
57
58        socket.on('vote', function (data) {
59            console.log('vote', data);
60            vote(socket.id, data.value);
61        });
62
63        socket.on('reset', function () {
64            console.log('reset');
65            reset_state();
66            send_update();
67        });
68
69        socket.on('disconnect', function () {
70            delete state.voters[socket.id];
71            send_update();
72        });
73    });
74};