-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
90 lines (71 loc) · 2.37 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
const express = require("express");
const app = require("express")();
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
const PORT = 3000;
const gameSockets = {};
const controllerSockets = {};
app.use("/", express.static(__dirname + "/public"));
httpServer.listen(process.env.PORT || PORT);
io.on("connection", (socket) => {
console.log(`Connected to Browser on ${socket.id}`);
socket.on("game connect", () => {
console.log(`Game Connected on ${socket.id}`);
gameSockets[socket.id] = {
socket: socket,
controllerId: undefined,
};
socket.emit("game connected");
});
socket.on("controller connect", (gameSocketId) => {
if (gameSockets[gameSocketId]) {
console.log(`Controller Connected on ${socket.id}`);
controllerSockets[socket.id] = {
socket: socket,
gameId: gameSocketId,
};
socket.emit("controller connected", true);
gameSockets[gameSocketId].controllerId = socket.id;
gameSockets[gameSocketId].socket.emit("controller connected", true);
socket.on("controller state change", (data) => {
if (gameSockets[gameSocketId]) {
gameSockets[gameSocketId].socket.emit(
"controller state change",
data
);
}
});
} else {
console.log(`Controller Connection Failed on ${socket.id}`);
socket.emit("controller connected", false);
}
});
socket.on("disconnect", () => {
if (gameSockets[socket.id]) {
console.log(`Game Disconnected on ${socket.id}`);
if (controllerSockets[gameSockets[socket.id].controllerId]) {
controllerSockets[gameSockets[socket.id].controllerId].socket.emit(
"controller connected",
false
);
controllerSockets[
gameSockets[socket.id].controllerId
].gameId = undefined;
}
delete gameSockets[socket.id];
}
if (controllerSockets[socket.id]) {
console.log(`Controller Disconnected on ${socket.id}`);
if (gameSockets[controllerSockets[socket.id].gameId]) {
gameSockets[controllerSockets[socket.id].gameId].socket.emit(
"controller connected",
false
);
gameSockets[
controllerSockets[socket.id].gameId
].controllerId = undefined;
}
delete controllerSockets[socket.id];
}
});
});