-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.js
241 lines (204 loc) · 6.41 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Create dictionaries for tracking hosts, clients, and rooms
let hosts = {};
let clients = {};
let rooms = {};
////////////
// Setup express web server and listen on port 3000
let express = require('express');
let app = express();
let port=Number(process.env.PORT || 3000);
let server = app.listen(port);
app.use(express.static('public'));
console.log("My socket server is running on port " + port);
////////////
// Start socket.io
let socket = require('socket.io');
// Connect it to the web server
let io = socket(server);
////////////
// Setup a connection
io.sockets.on('connection', newConnection);
function newConnection(socket) {
// Inform incoming connection of its ID
console.log('\n' + socket.id + ' is attempting connection...');
socket.emit('id', socket.id);
// Process a request to join.
socket.on('join', function (data) {
// If request is from a client...
if (data.name == 'client') {
console.log("Verifying client...");
// If the roomId field is not null
if (data.roomId != null) {
// Search existing roomIds for a match
console.log("Searching for existing room ID...");
if (rooms[data.roomId] != null) {
// Add client to room with all connected clients
socket.join(data.name);
// Add client and corresponding data to clients dictionary
// by socket ID
clients[socket.id] = {
type: data.name,
roomId: data.roomId
}
// Add client to its own room and to host room by room ID
socket.join([socket.id, data.roomId]);
console.log('Client added to room '+data.roomId+'.\tNumber of clients: ' + Object.keys(clients).length);
// Send match confirmation back to client
socket.emit("found", {status: true});
}
else {
// Notify client of failure to match
socket.emit("found", {status: false});
}
}
}
else if (data.name == 'host') {
// If the attempted connection is from a host...
// Store a transmitted room ID if it exists, otherwise
// generate a random gemstone name as room ID.
let roomId = null;
if (data.roomId === null || data.roomId === 'undefined') {
roomId = makeIdFromList();
}
else {
roomId = data.roomId;
}
// Add client and corresponding data to devices dictionary
// by socket ID
let hostData = {
type: data.name,
roomId: roomId
};
hosts[socket.id] = hostData;
rooms[roomId] = socket.id;
// Add host to "host" room, its own room by room ID, and to a room
// with its clients by room ID.
socket.join([data.name, 'host:'+hostData.roomId, hostData.roomId]);
// Send clients room ID back to host
socket.emit("hostConnect", hostData);
console.log('Host added with room ID of ' + hostData.roomId + '.\tNumber of hosts: ' + Object.keys(hosts).length);
}
else {
console.log('warning: data type not recognized.')
}
})
//// Process device disconnects.
socket.on('disconnect', function () {
console.log('\n' + socket.id + ' has been disconnected!');
if (clients[socket.id] != null) {
// If the device is a client, delete it
delete clients[socket.id];
console.log('Client removed.\tNumber of clients: ' + Object.keys(clients).length);
// Notify hosts that client has disconnected.
socket.in('host').emit('clientDisconnect', {id: socket.id});
}
else if (hosts[socket.id] != null) {
// If the device is a host, delete it
let roomId = hosts[socket.id].roomId;
delete hosts[socket.id];
console.log('Host with ID ' + roomId + ' removed.\tHumber of hosts: ' + Object.keys(hosts).length);
// Remove corresponding room
let key = getKeyByValue(rooms, socket.id);
if (key != null) {
delete rooms[key];
}
// TODO: add handling for all clients connected to host when host
// is disconnected.
}
})
//// Process client connects.
socket.on('clientConnect', onClientConnect);
function onClientConnect(data) {
if (rooms[data.roomId] != null) {
console.log('clientConnect message received from ' + socket.id + ' for room ' + data.roomId + ".");
socket.in('host:'+data.roomId).emit('clientConnect', {id: socket.id, roomId: data.roomId});
}
}
//// Reroute data sent between clients and hosts
socket.on('sendData', sendData);
function sendData(data) {
let packet = {...data};
packet.id = socket.id;
// If room ID is valid...
if (rooms[data.roomId] != null) {
if (clients[socket.id] != null) {
// And if device is a client, send to corresponding host
socket.in('host:'+data.roomId).emit('receiveData', packet);
}
else if (hosts[socket.id] != null) {
// And if device is a host, send to corresponding clients
socket.broadcast.in(data.roomId).emit('receiveData', packet);
}
}
}
}
////////////
// Utility Functions
function searchRoomId(roomId_, array_) {
for (let i = 0; i < array_.length; i++) {
if (array_[i].roomId == roomId_) {
return {
item: array_[i],
index: i
};
}
}
}
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
////////////
// Gemstone room ID generator
const roomNames =
["agate",
"amber",
"amethyst",
"barite",
"beryl",
"bloodstone",
"coral",
"crystal",
"diamond",
"emerald",
"fluorite",
"garnet",
"goldstone",
"jade",
"jasper",
"moonstone",
"onyx",
"opal",
"pearl",
"peridot",
"quahog",
"quartz",
"ruby",
"sapphire",
"sardonyx",
"sunstone",
"tigereye",
"topaz",
"turquoise",
"zircon"]
const roomIds = randomNoRepeats(roomNames);
function randomNoRepeats(array) {
let copy = array.slice(0);
return function() {
if (copy.length < 1) { copy = array.slice(0); }
let index = Math.floor(Math.random() * copy.length);
let item = copy[index];
copy.splice(index, 1);
return {id: item, length: copy.length};
};
}
function makeIdFromList() {
for (let i = 0; i < roomNames.length; i++) {
let text = roomIds().id;
let room = searchRoomId(text, hosts);
if (room == null) {
return text;
}
}
console.log(hosts.length + " hosts detected. No names available.");
return null;
}