-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
505 lines (438 loc) · 14 KB
/
server.js
File metadata and controls
505 lines (438 loc) · 14 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
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
498
499
500
501
502
503
504
505
/*
*@autor: Rio 3D Studios
*@description: java script server that works as master server of the Basic Example of WebGL Multiplayer Kit
*/
var express = require("express"); //import express NodeJS framework module
var app = express(); // create an object of the express module
var http = require("http").Server(app); // create a http web server using the http library
var io = require("socket.io")(http); // import socketio communication module
const qs = require("qs");
const fs = require("fs");
const axios = require("axios");
var shortId = require("shortid"); //import shortid module
const config = require("./public/config/secret");
const csurf = require("csurf");
var indexRouter = require("./routes/index");
var request = require("request");
// app.use('/', indexRouter);
var session = require("express-session");
app.use(
session({
secret: "@#@$MYSIGN#@$#$",
resave: false,
saveUninitialized: true,
})
);
// app.use(function(req, res, next) {
// var token = req.csrfToken();
// res.cookie("XSRF-TOKEN", token);
// res.locals.csrfToken = token;
// next();
// });
const cookieParser = require("cookie-parser");
app.use(cookieParser());
// const csrfMiddleware = csurf({
// cookie: true
// });
// app.use(csrfMiddleware);
app.get("/kakaoLogin", (req, res) => {
console.log("Get request");
console.log(`idToken in get kakao ${req.query.idToken}`);
res.cookie("cookieToken", req.query.idToken);
res.redirect("/home");
res.send();
});
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// bootstrap module
app.use("/js", express.static(__dirname + "/node_modules/bootstrap/dist/js")); // redirect bootstrap JS
app.use("/css", express.static(__dirname + "/node_modules/bootstrap/dist/css")); // redirect CSS bootstrap
// routes settings
// app.use(
// "/public/TemplateData",
// express.static(__dirname + "/public/TemplateData")
// );
// app.use("/public/Build", express.static(__dirname + "/public/Build"));
app.use(
"/public/TemplateDataPlaza",
express.static(__dirname + "/public/TemplateDataPlaza")
);
app.use("/public/BuildPlaza", express.static(__dirname + "/public/BuildPlaza"));
app.set("views", __dirname + "/public/views");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
const kakaoConfig = {
clientID: config.REST_API_KEY,
redirectUri: config.REDIRECT_URI,
};
// Page View
app.get("/", (req, res) => {
res.render("index");
});
app.get("/plaza", (req, res) => {
user = axios({
method: "get",
url: "http://172.30.1.33:8000/user/",
headers: {
token: req.cookies["cookieToken"],
},
}).then(function (response) {
console.log(response);
user = response.data;
console.log(user);
res.render("plaza", {
userName: user.userName,
univName: user.univName,
kakaoEmail: user.kakaoEmail,
kakaoId: user.kakaoId,
nickName: user.nickName,
});
});
});
app.get("/wait", (req, res) => {
user = axios({
method: "get",
url: "http://172.30.1.33:8000/user/",
headers: {
token: req.cookies["cookieToken"],
},
}).then(function (response) {
// console.log(response);
user = response.data;
// console.log(user);
res.render("waitRoom", {
userName: user.userName,
univName: user.univName,
kakaoEmail: user.kakaoEmail,
kakaoId: user.kakaoId,
nickName: user.nickName,
});
});
});
app.get("/game", (req, res) => {
user = axios({
method: "get",
url: "http://172.30.1.33:8000/user/",
headers: {
token: req.cookies["cookieToken"],
},
}).then(function (response) {
// console.log(response);
user = response.data;
// console.log(user);
res.render("gameScene", {
userNameTest: "sdf",
userName: user.userName,
univName: user.univName,
kakaoEmail: user.kakaoEmail,
kakaoId: user.kakaoId,
nickName: user.nickName,
});
});
});
app.get("/home", (req, res) => {
user = axios({
method: "get",
url: "http://172.30.1.33:8000/user/",
headers: {
token: req.cookies["cookieToken"],
},
}).then(function (response) {
user = response.data;
res.render("mainPage2", {
userNameTest: "sdf",
userName: user.userName,
univName: user.univName,
kakaoEmail: user.kakaoEmail,
idToken: req.cookies["cookieToken"],
kakaoId: user.kakaoId,
nickName: user.nickName,
});
});
// console.log(user.user);
setTimeout(() => {
// console.log("token이다" + req.cookies["cookieToken"]);
}, 100);
});
app.get("/ranking/:part", async (req, res) => {
const { part } = req.params;
const user = await axios({
method: "get",
url: "http://172.30.1.33:8000/user/",
headers: {
token: req.cookies["cookieToken"],
},
});
const URL = "http://172.30.1.33:8000/ranking/" + part;
console.log("URL: ${URL}");
res.render("ranking", {
userName: user.userName,
univName: user.univName,
kakaoEmail: user.kakaoEmail,
idToken: req.cookies["cookieToken"],
nickName: user.nickName,
part,
});
});
var clients = {}; // to storage clients
var clientLookup = {}; // clients search engine
var sockets = {}; //// to storage sockets
//open a connection with the specific client
io.on("connection", function (socket) {
//print a log in node.js command prompt
console.log("A user ready for connection!");
//to store current client connection
var currentUser;
socket.on("newUserConnect", function (name) {
socket.name = name;
io.sockets.emit("updateMessage", {
name: "SERVER",
message: name + "님이 접속했습니다.",
});
});
socket.on("userDisconnect", function () {
io.sockets.emit("updateMessage", {
name: "SERVER",
message: socket.name + "님이 퇴장했습니다.",
});
});
socket.on("sendMessage", function (data) {
data.name = socket.name;
io.sockets.emit("updateMessage", data);
});
//create a callback fuction to listening EmitJoin() method in NetworkMannager.cs unity script
socket.on("LOGIN", function (_data) {
console.log("[INFO] LOGIN received !!! ");
var data = JSON.parse(_data);
// fills out with the information emitted by the player in the unity
let currentURL = data.url;
//add currentUser in clients list
if (!(currentURL in clients)) clients[currentURL] = [];
const spawnPos = [
"-126.48:38.48:-146.3",
"-135.39:38.48:-146.3",
"-65:122.63:13.6",
"-55:122.63:13.6",
"-45:122.63:13.6",
];
let posData = data.position;
let rotationAngle = "0";
if (currentURL.includes("game")) {
posData = spawnPos[clients[currentURL].length];
rotationAngle = "180";
}
currentUser = {
kakaoId: data.name,
avatar: data.avatar,
name: data.userName,
position: posData,
rotation: rotationAngle,
id: socket.id, //alternatively we could use socket.id
socketID: socket.id, //fills out with the id of the socket that was open
animation: "",
health: 100,
maxHealth: 100,
kills: 0,
timeOut: 0,
isDead: false,
playingURL: currentURL,
kakaoUniqueId: data.name,
};
console.log("[INFO] socket" + currentUser.socketID);
console.log("[INFO] player kakaoId " + currentUser.kakaoId + ": logged!");
console.log("[INFO] currentUser.position " + currentUser.position);
clients[currentURL].push(currentUser);
//add client in search engine
clientLookup[currentUser.id] = currentUser;
console.log(
`[INFO ${currentURL}]-Total accesor: ${clients[currentURL].length}`
);
/*********************************************************************************************/
//send to the client.js script
socket.emit(
"LOGIN_SUCCESS",
currentUser.id,
currentUser.name,
currentUser.avatar,
currentUser.position,
currentUser.kakaoUniqueId
);
//spawn all connected clients for currentUser client
clients[currentURL].forEach(function (i) {
if (i.id != currentUser.id) {
//send to the client.js script
socket.emit(
"SPAWN_PLAYER",
i.id,
i.name,
i.avatar,
i.position,
i.kakaoUniqueId
);
} //END_IF
}); //end_forEach
// spawn currentUser client on clients in broadcast
socket.broadcast.emit(
"SPAWN_PLAYER",
currentUser.id,
currentUser.name,
currentUser.avatar,
currentUser.position,
currentUser.kakaoUniqueId
);
}); //END_SOCKET_ON
//create a callback fuction to listening EmitPing() method in NetworkMannager.cs unity script
socket.on("PING", function (_pack) {
//console.log('_pack# '+_pack);
var pack = JSON.parse(_pack);
console.log(`pack data parsing: ${pack.kakaoUniqueId}`);
console.log("message from user# " + socket.id + ": " + pack.msg);
console.log(`User arrived at the track: ${currentUser.kakaoId}`);
// timer.stopTimer(timerInterv);
let endTime = new Date().getTime();
console.log("-->", endTime);
if (currentUser.kakaoId === pack.kakaoUniqueId) {
console.log(`-> Axios: curr: ${currentUser.kakaoId}`);
console.log(`-> Axios: ping: ${pack.kakaoUniqueId}`);
axios({
method: "get",
url: "http://172.30.1.33:8000/game/api/update-record",
headers: {
kakaoId: currentUser.kakaoId,
currentURL: currentUser.playingURL,
endTime: parseInt(endTime),
},
}).then(function (response) {
console.log(`게임 종료 !\n${response}`);
});
}
//emit back to NetworkManager in Unity by client.js script
socket.emit("PONG", socket.id, pack.msg);
});
//create a callback fuction to listening method in NetworkMannager.cs unity script
socket.on("RESPAWN", function (_info) {
var info = JSON.parse(_info);
if (currentUser) {
currentUser.isDead = false;
currentUser.health = currentUser.maxHealth;
socket.emit(
"RESPAWN_PLAYER",
currentUser.id,
currentUser.name,
currentUser.avatar,
currentUser.position,
currentUser.kakaoUniqueId
);
socket.broadcast.emit(
"SPAWN_PLAYER",
currentUser.id,
currentUser.name,
currentUser.avatar,
currentUser.position,
currentUser.kakaoUniqueId
);
console.log("[INFO] User " + currentUser.name + " respawned!");
}
}); //END_SOCKET_ON
//create a callback fuction to listening EmitMoveAndRotate() method in NetworkMannager.cs unity script
socket.on("MOVE_AND_ROTATE", function (_data) {
var data = JSON.parse(_data);
if (currentUser) {
currentUser.position = data.position;
currentUser.rotation = data.rotation;
// send current user position and rotation in broadcast to all clients in game
socket.broadcast.emit(
"UPDATE_MOVE_AND_ROTATE",
currentUser.id,
currentUser.position,
currentUser.rotation
);
}
}); //END_SOCKET_ON
//create a callback fuction to listening EmitAnimation() method in NetworkMannager.cs unity script
socket.on("ANIMATION", function (_data) {
var data = JSON.parse(_data);
if (currentUser) {
currentUser.timeOut = 0;
//send to the client.js script
//updates the animation of the player for the other game clients
socket.broadcast.emit(
"UPDATE_PLAYER_ANIMATOR",
currentUser.id,
data.animation
);
} //END_IF
}); //END_SOCKET_ON
//create a callback fuction to listening EmitAnimation() method in NetworkMannager.cs unity script
socket.on("ATTACK", function () {
if (currentUser) {
// console.log("attack received");
socket.broadcast.emit("UPDATE_ATTACK", currentUser.id);
}
}); //END_SOCKET_ON
//create a callback fuction to listening EmitPhisicstDamage method in NetworkMannager.cs unity script
socket.on("PHISICS_DAMAGE", function (_data) {
var data = JSON.parse(_data);
if (currentUser) {
var target = clientLookup[data.targetId];
var _damage = 1;
// if health target is not empty
if (target.health - _damage > 0) {
// console.log("player: "+target.name+"receive damage from : "+currentUser.name);
// console.log(target.name+"health: "+ target.health);
target.health -= _damage; //decrease target health
} else {
if (!target.isDead) {
target.isDead = true; //target is dead
target.kills = 0;
//console.log("currentuser"+currentUser.name+" kills: "+currentUser.kills);
currentUser.kills += 1;
jo_pack = {
targetId: data.targetId,
};
//emit only for the currentUser
socket.emit("DEATH", jo_pack.targetId);
//emit to all connected clients in broadcast
socket.broadcast.emit("DEATH", jo_pack.targetId);
} //END_ if
} //END_ELSE
damage_pack = {
targetId: data.targetId,
targetHealth: target.health,
};
socket.emit(
"UPDATE_PHISICS_DAMAGE",
damage_pack.targetId,
damage_pack.targetHealth
);
socket.broadcast.emit(
"UPDATE_PHISICS_DAMAGE",
damage_pack.targetId,
damage_pack.targetHealth
);
} //END_IF
}); //END_SOCKET_ON
// called when the user desconnect
socket.on("disconnect", function () {
if (currentUser) {
currentUser.isDead = true;
//send to the client.js script
//updates the currentUser disconnection for all players in game
socket.broadcast.emit("USER_DISCONNECTED", currentUser.id);
for (var i = 0; i < clients.length; i++) {
if (
clients[i].name == currentUser.name &&
clients[i].id == currentUser.id
) {
console.log("User " + clients[i].name + " has disconnected");
clients.splice(i, 1);
}
}
}
}); //END_SOCKET_ON
}); //END_IO.ON
http.listen(process.env.PORT || 3000, function () {
console.log("listening on *:3000");
});
console.log("------- server is running -------");