-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
497 lines (444 loc) · 14.2 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
var http = require('http'),
url = require('url'),
fs = require('fs'),
io = require('./index'),
sys = require('sys'),
send404 = function(res){
res.writeHead(404);
res.write('404');
res.end();
},
server = http.createServer(function(req, res){
// your normal server code
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Welcome. Try the <a href="/client/index.html">stillepost</a> example.</h1>');
res.end();
break;
default:
var contentType;
var encoding;
if (/\.(swf)$/.test(path)){
contentType = 'application/x-shockwave-flash';
encoding = 'binary';
} else
if (/\.(html)$/.test(path)){
contentType = 'text/html';
encoding = 'utf8';
} else
if (/\.(js)$/.test(path)){
contentType = 'text/javascript';
encoding = 'utf8';
} else
if (/\.(png)$/.test(path)){
contentType = 'image/png';
encoding = 'binary';
} else
if (/\.(jpg)$/.test(path)){
contentType = 'image/jpg';
encoding = 'binary';
} else
if (/\.(css)$/.test(path)){
contentType = 'text/css';
encoding = 'utf8';
}
if (/\.(eot)$/.test(path)){
contentType = 'application/vnd.ms-fontobject';
encoding = 'binary';
}
if (/\.(ttf)$/.test(path)){
contentType = 'font/ttf';
encoding = 'binary';
}
if (/\.(woff)$/.test(path)){
contentType = 'application/x-woff';
encoding = 'binary';
}
if(contentType != null && encoding != null) {
try {
res.writeHead(200, {'Content-Type':contentType});
res.write(fs.readFileSync(__dirname + path, encoding ), encoding);
res.end();
} catch(e){
send404(res);
}
} else {
send404(res);
}
send404(res);
break;
}
});
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function() {};
F.prototype = o;
return new F();
};
};
function create_json(type, property, data) {
var o = new Object();
o.type = type;
o.property = property;
o.value = data;
return JSON.stringify(o);
};
server.listen(6060);
// changes of the application state are pushed to all clients
// changes belonging to a running game are only pushed to participants,
// i.e. changes of the game object as well as draw-events
var player_prototyp = {
name: 'anonymous',
url: 'img/default_player.jpg',
sessionId: 'TBD', // mandatoryâ
send: function(type, property, data) {
var message = create_json(type, property, data);
for (clientIdx in io.clients) {
var client = io.clients[clientIdx];
if (client != null && client.sessionId == this.sessionId) {
console.log("Sending to "+this.sessionId+ ": " + message);
client.send(message);
}
}
},
to_s: function() {
return this.name + " (sessionId="+this.sessionId+")";
},
client_info: function() {
var result = new Object();
result.name = this.name;
result.sessionId = this.sessionId;
result.url = this.url;
return result;
}
};
var game_prototyp = {
name: "mandatory",
state: 'OPEN', // one of "OPEN", "RUNNING", "FINISHED"
current: undefined, // session ID of current player
pass_on: function() {
},
owner: function() {
return players[0];
},
players: null, // array of session ID's of current players, passing uses the order given here
send: function(type, property, data) {
console.log("Sending to "+this.players.length+" participants of " + this.name + " ...");
var i;
for(i=0; i< this.players.length; i++) {
app.players[this.players[i]].send(type, property, data);
}
},
to_s: function() {
return this.name + " (" + this.state + "/current=" + this.current+")";
},
client_info: function() {
var result = new Object();
result.name = this.name;
result.players = this.players;
result.state = this.state;
result.draw_history = [];
return result;
},
start: function() {
this.state = "RUNNING";
this.current = this.players[0];
},
pass_on: function() {
var idx = this.players.indexOf(this.current) + 1;
this.current = this.players[idx];
if (this.current === undefined) {
this.state= "FINISHED";
}
},
remove_player: function(player) {
if (player.session_id == this.current) {
this.pass_on();
}
var idx = this.players.indexOf(player.sessionId);
if (idx != -1) {
this.players.splice(idx,1);
this.send("UPDATE", [ "game", "players" ], this.players);
if (this.players.length == 0) {
app.delete_game(this);
}
}
}
};
var app = {
players: new Object(), // sessionID => Player
games: new Object(), // name => Game
game_labels: [], // in sync with games, this one holds the names and keeps the order
create_player: function(sessionId) {
var new_player = Object.create(player_prototyp);
new_player.sessionId = sessionId;
this.players[sessionId] = new_player;
return new_player;
},
remove_player: function(player) {
for (var game_name in this.games) {
this.games[game_name].remove_player(player);
}
delete this.players[player.sessionId];
this.notify_players_updated();
},
notify_players_updated: function() {
app.send("UPDATE", ["players"], app.client_players());
},
create_game: function(sessionId, name) {
var new_game = Object.create(game_prototyp);
new_game.name = name;
new_game.players = [];
new_game.players.push(sessionId);
this.games[name] = new_game;
this.game_labels.push(name);
return new_game;
},
delete_game: function(game) {
delete this.games[game.name];
var idx = this.game_labels.indexOf(game.name);
this.game_labels.splice(idx,1);
this.send("UPDATE", ["games_list"], this.game_labels);
},
current_game: function(sessionId) {
for (var game_name in this.games) {
var game = this.games[game_name];
if (game.players.indexOf(sessionId) !== -1) {
return game;
}
}
return null;
},
send: function(type, property, data) {
var message = create_json(type, property, data);
console.log("Sending to all: " + message);
io.broadcast(message);
},
client_players: function() {
var result = new Object();
for (playerId in this.players) {
result[playerId] = this.players[playerId].client_info();
}
return result;
},
clean_player: function(player) {
// remove all games where player participates
var current_game = this.current_game(player.sessionId);
while (current_game !== null) {
console.log("Cleaning up player's "+player.sessionId+" games: " + current_game.name);
this.delete_game(current_game);
current_game = this.current_game(player.sessionId);
}
}
};
var to_array = function(o) {
var result = [];
for ( p in o) {
result.push(o[p]);
}
return result;
};
// client model
// Player object:
// player.name
// player.url
// Game object:
// game.current, id of current player
// game.players, array of player ids
// game.draw_history, player id => []
// Application object:
// app.me = Player object
// app.players, id => Player object
// app.game_list = [] // labels of games, the labels must be unique, i.e. they are used as ID
// app.game = Game Object
// server sends model updates to the client, e.g.
//Add new player (app.players["123"] does not exist):
// Add new player (app.players["123"] does not exist):
// { type: "UPDATE", property: [ "players", "123" ], value: { name: "newname", url: "http"} }
// Update:
// { type: "UPDATE", property: ["players", "123", "name"], value: "updatedname" }
// Delete (no value given):
// { type: "DELETE", property: [ "game_list", 0 ] }
// note: implementation can use delete on objects but should use splice(x,1) on arrays
// Add to draw history of current game
// { type: "PUSH", property: [ "game", "draw_history", "<sessionID>" ], value: {} }
// example communication, two player game
// client 1 connects
// server -> client1
// { type: "UPDATE", property: [ "game_list" ], value: [] }
// client1 updates profile
// server -> all
// { type: "UPDATE", property: [ "players", "<sessionId>", "name" ], value: [ "itsme" ] }
// client2 connects
// client1 creates a new game
// client1 -> server "create_game", payload: { game => "myGame" }
// server -> client1
// { type: "UPDATE", property: [ "game" ], value: { name: "myGame", players: [<sessionId>], state: "OPEN" } }
// server -> client1, client2 (alle clients)
// { type: "ADD", property: [ "game_list" ], value: "myGame" }
// client2 joins game
// server -> client2 (all participants of the game)
// { type: "UPDATE", property: [ "game" ], value: { name: "myGame", players: [<sessionId>], state: "OPEN" } }
// server -> client1, client2 (all participants of the game)
// { type: "ADD", property: [ "game", "players" ], value: <sessionId> }
// client1 starts game
// server -> client1, client2 (all participants of the game)
// { type: "UPDATE", property: [ "game", "state" ], value: { state: "RUNNING" } }
// { type: "UPDATE", property: [ "game", "current" ], value: <sessionId> } }
var ta= ["5"];
var io = io.listen(server);
io.on('connection', function(client) {
client.player = app.create_player(client.sessionId);
// letting the client know who he is should be the very first thing
client.player.send("UPDATE", ["sessionId"], client.sessionId);
app.notify_players_updated();
client.player.send("UPDATE", ["games_list"], app.game_labels);
client.on('message', function(message) {
console.log("Dispatching: " + message);
var msg = JSON.parse(message)
var arguments = msg.arguments;
if (msg.type == "draw") {
draw_line(arguments)
} else if (msg.type == "create_game") {
create_game(arguments);
} else if (msg.type == "join_game") {
join_game(arguments);
} else if (msg.type == "start_game") {
start_game(arguments);
} else if (msg.type == "pass_on") {
pass_on(arguments);
} else if (msg.type == "update_profile") {
update_profile(arguments);
} else if (msg.type == "get_game_participants") {
get_game_participants(arguments);
} else if (msg.type == "invite") {
invite(arguments);
}
});
client.on('disconnect', function() {
console.log("Player " + client.player.to_s() + " disconnected");
app.remove_player(client.player);
});
function create_game(data) {
// guard
if (data === undefined || data.name === undefined) {
console.log("Invalid data for creating game");
return;
}
app.clean_player(client.player);
console.log("Player " + client.player.to_s() + " creates game " + data.name);
var game = app.create_game(client.sessionId, data.name);
console.log("players: " + game.players.join(","));
client.player.send("UPDATE", ["game"], game.client_info());
app.send("UPDATE", ["games_list"], app.game_labels);
}
function update_profile(data) {
// guard
if (data === undefined || data.property === undefined) {
console.log("Invalid data for updating profile game");
return;
}
var player = client.player;
console.log("Player " + player.to_s() + " updates property " + data.property);
player[data.property] = data.value;
console.log("Player is now " + player.to_s());
app.send("UPDATE", ["players", client.sessionId, data.property], player[data.property]);
}
function join_game(data) {
// guard
if (data === undefined || data.name === undefined) {
console.log("Invalid data for joining game");
return;
}
var game = app.games[data.name];
if (game == undefined) {
console.log("Trying to join invalid game");
return;
}
var player = client.player;
app.clean_player(player);
console.log("Player " + player.name + " joins game " + game.name);
player.send("UPDATE", ["game"], game.client_info());
game.players.push(player.sessionId);
game.send("UPDATE", ["game", "players"], game.players);
}
function start_game(data) {
var player = client.player;
var game = app.current_game(player.sessionId);
if (game == null) {
console.log("Player "+ player.to_s() + " does not own a game to start");
return;
}
console.log("Player " + player.to_s() + " has started game " + game.name);
game.start();
game.send("UPDATE", ["game", "state"], game.state);
game.send("UPDATE", ["game", "current"], game.current);
}
function pass_on(data) {
var player = client.player;
var game = app.current_game(player.sessionId);
if (game == null) {
console.log("Player "+ player.to_s() + " does not own a game to start");
return;
}
game.pass_on();
game.send("UPDATE", ["game", "current"], game.current);
if (game.state == "FINISHED") {
console.log("Game over for " + game.to_s());
game.send("UPDATE", ["game", "state"], game.state);
app.delete_game(game);
}
}
function draw_line(data) {
var player = client.player;
var game = app.current_game(player.sessionId);
if (game == undefined) {
console.log("Error: can not broadcasting draw line event of player "+ player.to_s());
return;
}
console.log("Broadcasting draw line event of " + player.to_s() + ": " + JSON.stringify(data));
game.send("ADD", ["game", "draw_history", player.sessionId], data);
}
function get_game_participants(data) {
// a client has requested the list of participants of a a game in order to show it in the
// init_players list
var player = client.player;
if (data.name === undefined) {
return;
}
var game = app.games[data.name];
if (game === undefined) {
console.log("get_game_participants: "+ data.name + " not found");
return;
}
player.send("UPDATE", [ "games" , game.name], game.players);
}
function invite(data) {
// guard
if (data === undefined || data.invited_id === undefined || data.game == undefined) {
console.log("Need to know which player to invite");
return;
}
var invited = app.players[data.invited_id];
if (invited == undefined) {
console.log("Can not invite unknown player " + data.invited_id);
return;
}
var game = app.games[data.game];
if (game === undefined) {
console.log("Can not invite to unknown game");
return;
}
var player = client.player;
console.log("Player " + player.to_s() + " invites " + invited.to_s() + " to " + game.to_s());
invited.send("UPDATE", ["invited"], { "game" : data.game, "inviter" : player.sessionId});
}
});
function serialize(key, value) {
var data = new Object();
data.type = key;
data.arguments = value;
return JSON.stringify(data);
}