-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
113 lines (88 loc) · 2.84 KB
/
server.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var http = require('http');
var express = require('express');
var WSS = require('ws').Server;
var app = express().use(express.static('public'));
var server = http.createServer(app);
//server.listen(process.env.PORT);
server.listen(8080, '127.0.0.1');
var showResults = false
var cards = [];
var wss = new WSS({ port: 8081 });
wss.on('connection', function(socket) {
for(var i=0; i<cards.length; i++) {
var item = cards[i];
var json = JSON.stringify({ text: item.name, category: item.category, id: i, votes: item.votes });
console.log("Sending to clients: " + json);
socket.send(json);
json = JSON.stringify({type: 'showresults'});
console.log("Sending to clients: " + json);
socket.send(json);
}
socket.on('message', function(message) {
console.log("Received: " + message);
var obj = JSON.parse(message);
if(typeof obj.type != 'undefined'){
switch (obj.type) {
case 'updatecategory':
updatedCategory(obj.id, obj.category);
break;
default:
break;
}
return;
}
if(typeof obj.showResults != 'undefined'){
wss.clients.forEach(function each(client) {
var json = JSON.stringify({type: 'showresults'});
console.log("Sending to clients: " + json);
client.send(json);
});
}
//If a vote feature
if(typeof obj.voted != 'undefined'){
var id = obj.id;
console.log(obj.voted + ' = '+ cards[id].votes);
votes = cards[id].votes + 1;
cards[id].votes = votes;
wss.clients.forEach(function each(client) {
var json = JSON.stringify({id: id, votes: votes });
console.log("Sending to clients: " + json);
client.send(json);
});
return;
}
//work out what the user sent to us
if(typeof obj.text != 'undefined'){
var text = obj.text;
var category = obj.category;
var id = obj.id;
var votes = 0;
if (typeof id == 'undefined') {
id = addCardToArray(text, category);
} else {
cards[id] = {name: text, category: category};
}
wss.clients.forEach(function each(client) {
var json = JSON.stringify({ text: text, category: category, id: id, votes: votes });
console.log("Sending to clients: " + json);
client.send(json);
});
}
});
socket.on('close', function() {
});
});
function updatedCategory(id, category){
cards[id].category = category;
var text = cards[id].name;
var votes = cards[id].votes;
wss.clients.forEach(function each(client) {
var json = JSON.stringify({ text: text, category: category, id: id, votes: votes });
console.log("Sending to clients: " + json);
client.send(json);
});
}
function addCardToArray(text, category){
cards.push({name: text, category: category, votes: 0 });
return cards.length-1;
}