-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
193 lines (171 loc) · 6.06 KB
/
server.js
File metadata and controls
193 lines (171 loc) · 6.06 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
const WebSocket = require("ws").Server;
const PLAYERS = Object.freeze({ PLAYER_X: "PLAYER_X", PLAYER_O: "PLAYER_O" });
const startwebSocketServer = (port) => {
const socket = new WebSocket({ port: port });
socket.on("listening", () => {
console.log("WebSocket server is Listening on port", port);
});
let isPlayerX = true;
const players = {};
let closedConnectionName;
socket.on("error", (error) => {
console.error("Error when connecting websocket", error);
});
socket.on("connection", (ws) => {
let clientSize = socket.clients.size;
if (!ws) return;
ws.on("message", (message) => {
message = JSON.parse(message);
if (message.type === "name") {
//DEFINING SOCKET CONNECTION
if (isPlayerX && clientSize % 2 !== 0) {
ws.playerName = PLAYERS.PLAYER_X;
ws.connectionNumber = `${clientSize} connection`;
players[`${clientSize} connection`] = [];
players[`${clientSize} connection`].push(ws);
isPlayerX = false;
} else if (isPlayerX && clientSize % 2 === 0 && closedConnectionName) {
//When existing playerX is reconnects
ws.playerName = PLAYERS.PLAYER_X;
ws.connectionNumber = closedConnectionName;
players[closedConnectionName].push(ws);
isPlayerX = false;
} else if (!isPlayerX && clientSize % 2 == 0) {
//When new PlayerO is connected
ws.playerName = PLAYERS.PLAYER_O;
ws.connectionNumber = `${clientSize - 1} connection`;
if (players[`${clientSize - 1} connection`])
players[`${clientSize - 1} connection`].push(ws);
isPlayerX = true;
} else if (!isPlayerX && clientSize % 2 !== 0 && closedConnectionName) {
//When exisiting PlayerO reconnects
ws.playerName = PLAYERS.PLAYER_O;
ws.connectionNumber = closedConnectionName;
players[closedConnectionName].push(ws);
isPlayerX = true;
} else if (!isPlayerX && clientSize % 2 !== 0) {
//When exisiting PlayerO disconnects and clientsize is odd then assign new connection for it
ws.playerName = PLAYERS.PLAYER_X;
ws.connectionNumber = `${clientSize} connection`;
players[`${clientSize} connection`] = [];
players[`${clientSize} connection`].push(ws);
isPlayerX = false;
}
socket.clients.forEach((client) => {
if (client === ws) {
client.send(
JSON.stringify({
name: ws.playerName,
type: "assignName",
})
);
}
});
return;
}
socket.clients.forEach((client) => {
let findClientToSendData;
const { connectionNumber } = ws;
if (!connectionNumber) return;
//PLAYERS CAN PLAY ONLY IN PAIR 2,4,6....
if (players?.[connectionNumber]?.length % 2 !== 0) return;
if (connectionNumber === client.connectionNumber) {
const index = players[connectionNumber]?.indexOf(ws);
if (index !== -1) {
findClientToSendData = players[connectionNumber][1 - index];
}
}
//sending data to eachother not to themselves
if (findClientToSendData) {
if (message.type === "isPair") {
client.send(
JSON.stringify({
name: findClientToSendData.playerName,
type: "isPair",
data: {
isPair: players[connectionNumber]?.length % 2 === 0,
},
})
);
}
if (message.type === "move") {
client.send(
JSON.stringify({
name: findClientToSendData.playerName,
type: "move",
data: {
PLAYER_O: message.data.PLAYER_O,
PLAYER_X: message.data.PLAYER_X,
},
})
);
}
if (message.type === "turn") {
client.send(
JSON.stringify({
name: findClientToSendData.playerName,
type: "turn",
data: {
isCircleTurn: message.data.isCircleTurn,
},
})
);
}
if (message.type === "endGame") {
client.send(
JSON.stringify({
name: findClientToSendData.playerName,
type: "endGame",
data: { isDraw: message.data.isDraw },
})
);
}
}
});
});
ws.on("close", () => {
clientSize = socket.clients.size;
//When Client is closed then also remove player from playersObj
Object.keys(players).forEach((key) => {
const index = players[key].findIndex((player) => ws === player);
if (index !== -1) {
closedConnectionName = key;
players[key].splice(index, 1);
socket.clients.forEach((client) => {
//This is the case to handle when user reconnects or disconnects refresh the state of the game
if (client?.connectionNumber === closedConnectionName) {
client.send(
JSON.stringify({
type: "disconnect",
data: { isPair: clientSize % 2 === 0 },
})
);
}
});
}
if (players[key].length === 0) {
delete players[key];
closedConnectionName = null;
}
});
isPlayerX = ws.playerName === PLAYERS.PLAYER_X;
//when no players exists then new player is assign as PlayerX
if (Object.keys(players).length <= 0) {
isPlayerX = true;
}
console.log(
`a websocket connection is closed for player ${ws.playerName}`
);
});
ws.on("error", (error) => {
console.log("WebSocket error ", error.message);
});
console.log(
`${clientSize} ${
clientSize === 1 ? "client is" : "clients are"
} connected`
);
});
};
const PORTNO = 5501;
startwebSocketServer(PORTNO);