This repository was archived by the owner on Dec 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
505 lines (439 loc) · 17.5 KB
/
Server.cpp
File metadata and controls
505 lines (439 loc) · 17.5 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
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <string>
#include <iostream>
#include <vector>
#include <thread>
#include <fstream>
#include <algorithm>
#pragma comment (lib, "Ws2_32.lib")
#define defaultIP "127.0.0.1"
#define defaultPort "3504"
#define defaultBufferLen 512
using namespace std;
/*Structure definitions*/
struct serverSettings {
int gamemode = 0, map = 0, difficulty = 0, minPlayers = 0, maxPlayers = 0, maxConnections = 0;
};
struct client {
int ID;
SOCKET socket;
boolean isRunning;
};
/*Function prototypes*/
void serverSetup(serverSettings*);
void clientProcess(client&, serverSettings&);
ofstream writeFile;
int connectedClients = 0, currentPlayers = 0, tempIndex = -1;
static string gamemodeNames[3] = { "Deathmatch", "Capture The Flag", "Blood Diamond" };
static string mapNames[3] = { "Tower", "Outback", "Hereford Base" };
static string difficultyNames[3] = { "Easy", "Challenging", "Veteran" };
time_t t;
int main() {
serverSettings settings;
serverSetup(&settings);
writeFile.open("serverDetails.txt");
writeFile << defaultIP << endl;
writeFile << defaultPort << endl;
writeFile.close();
WSAData wsaData;
addrinfo hints, * server = NULL;
SOCKET listenerSock = INVALID_SOCKET, clientSock = INVALID_SOCKET;
string message = "";
vector<client> clients(settings.maxConnections);
vector<thread> clientThreads(settings.maxConnections);
int returnCode, tempClientID, clientID = 1, connectionsMade = 0;
boolean runServer = true;
writeFile.open("serverLog.txt");
cout << "Server setup: " << endl;
cout << "IP: " << defaultIP << endl;
cout << "PORT: " << defaultPort << endl;
cout << "Gamemode: " << gamemodeNames[settings.gamemode - 1] << endl;
cout << "Map: " << mapNames[settings.map - 1] << endl;
cout << "Difficulty: " << difficultyNames[settings.difficulty - 1] << endl;
cout << "Minimum players: " << settings.minPlayers << endl;
cout << "Maximum players: " << settings.maxPlayers << endl;
cout << "Maximum connections: " << settings.maxConnections << endl;
writeFile << "Server setup: " << endl;
writeFile << "IP: " << defaultIP << endl;
writeFile << "PORT: " << defaultPort << endl;
writeFile << "Gamemode: " << gamemodeNames[settings.gamemode - 1] << endl;
writeFile << "Map: " << mapNames[settings.map - 1] << endl;
writeFile << "Difficulty: " << difficultyNames[settings.difficulty - 1] << endl;
writeFile << "Minimum players: " << settings.minPlayers << endl;
writeFile << "Maximum players: " << settings.maxPlayers << endl;
writeFile << "Maximum connections: " << settings.maxConnections << endl;
/*Initialise Winsock*/
returnCode = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (returnCode != 0) {
t = time(NULL);
cout << "Failed to initialise Winsock. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to initialise Winsock. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
return 1;
}
t = time(NULL);
cout << "Winsock successfully initialised." << endl;
writeFile << "Winsock successfully initialised. - " << asctime(localtime(&t)) << endl;
/*Set up hints*/
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
/*Get address information*/
returnCode = getaddrinfo(defaultIP, defaultPort, &hints, &server);
if (returnCode != 0) {
t = time(NULL);
cout << "Failed to get address info. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to get address info. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
WSACleanup();
return 1;
}
t = time(NULL);
cout << "Address information recieved." << endl;
writeFile << "Address information recieved. - " << asctime(localtime(&t)) << endl;
/*Create listener socket*/
listenerSock = socket(server->ai_family, server->ai_socktype, server->ai_protocol);
if (listenerSock == INVALID_SOCKET) {
t = time(NULL);
cout << "Failed to create listener socker. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to create listener socker. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
freeaddrinfo(server);
closesocket(listenerSock);
WSACleanup();
return 1;
}
t = time(NULL);
cout << "Listener socket created." << endl;
writeFile << "Listener socket created. - " << asctime(localtime(&t)) << endl;
setsockopt(listenerSock, SOL_SOCKET, SO_REUSEADDR, 0, 0);
/*Bind address to listener socker*/
returnCode = bind(listenerSock, server->ai_addr, (int)server->ai_addrlen);
if (returnCode == SOCKET_ERROR) {
t = time(NULL);
cout << "Failed to bind address to listener port. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to bind address to listener port. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
freeaddrinfo(server);
closesocket(listenerSock);
WSACleanup();
return 1;
}
t = time(NULL);
cout << "Address bound to listener socket." << endl;
writeFile << "Address bound to listener socket. - " << asctime(localtime(&t)) << endl;
/*Listen for inbound connections*/
t = time(NULL);
cout << "Listening for connections." << endl;
writeFile << "Listening for connections. - " << asctime(localtime(&t)) << endl;
listen(listenerSock, SOMAXCONN);
/*Initialise client list*/
for (int i = 0; i < settings.maxConnections; i++) {
clients[i] = { -1, INVALID_SOCKET, false};
}
/*Run clients*/
while (runServer) {
t = time(NULL);
cout << "Connected Clients: " << connectedClients << endl;
writeFile << "Connected Clients: " << connectedClients << " - " << asctime(localtime(&t)) << endl;
cout << "Current players: " << currentPlayers << endl;
writeFile << "Current players: " << currentPlayers << " - " << asctime(localtime(&t)) << endl;
/*Add new connection*/
if (connectedClients < settings.maxConnections) {
/*Check if there are any spectators that could be converted to players*/
while (currentPlayers < settings.maxPlayers && connectedClients > currentPlayers) {
for (int i = 0; i < settings.maxConnections; i++) {
if (currentPlayers == settings.maxPlayers) continue;
if (clients[i].isRunning == false && clients[i].ID != -1) {
clients[i].isRunning = true;
currentPlayers++;
}
}
}
/*Only accept new connections if there is space*/
clientSock = accept(listenerSock, NULL, NULL);
connectedClients = 0;
tempClientID = -1;
for (int i = 0; i < settings.maxConnections; i++) {
if (clients[i].socket == INVALID_SOCKET && tempClientID == -1) {
clients[i].socket = clientSock;
clients[i].ID = clientID;
clients[i].isRunning = false;
tempClientID = i;
clientID++;
}
if (clients[i].socket != INVALID_SOCKET) {
connectedClients++;
connectionsMade++;
}
}
if (currentPlayers < settings.maxPlayers) {
clients[tempClientID].isRunning = true;
currentPlayers++;
}
t = time(NULL);
cout << "Client " << clients[tempClientID].ID << " accepted." << endl;
writeFile << "Client " << clients[tempClientID].ID << " accepted. - " << asctime(localtime(&t)) << endl;
if (connectedClients < settings.minPlayers) {
t = time(NULL);
cout << "Waiting for more clients to start match. " << connectedClients << " / " << settings.minPlayers << " in queue." << endl;
writeFile << "Waiting for more clients to start match. " << connectedClients << " / " << settings.minPlayers << " in queue. - " << asctime(localtime(&t)) << endl;
}
message = to_string(clients[tempClientID].ID);
send(clients[tempClientID].socket, message.c_str(), strlen(message.c_str()), 0);
clientThreads[tempClientID] = thread(clientProcess, ref(clients[tempClientID]), ref(settings));
clientThreads[tempClientID].detach();
clientThreads[tempClientID].~thread();
}
else {
/*Cant accept any more clients - Close socket until there is space*/
t = time(NULL);
cout << "Closing listener socket whilst server is full." << endl;
writeFile << "Closing listener socket whilst server is full. - " << asctime(localtime(&t)) << endl;
closesocket(listenerSock);
while (connectedClients == settings.maxConnections) {
}
/*Set up hints*/
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
/*Get address information*/
returnCode = getaddrinfo(defaultIP, defaultPort, &hints, &server);
if (returnCode != 0) {
t = time(NULL);
cout << "Failed to get address info. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to get address info. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
WSACleanup();
return 1;
}
t = time(NULL);
cout << "Address information recieved." << endl;
writeFile << "Address information recieved. - " << asctime(localtime(&t)) << endl;
/*Create listener socket*/
listenerSock = socket(server->ai_family, server->ai_socktype, server->ai_protocol);
if (listenerSock == INVALID_SOCKET) {
t = time(NULL);
cout << "Failed to create listener socker. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to create listener socker. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
freeaddrinfo(server);
closesocket(listenerSock);
WSACleanup();
return 1;
}
t = time(NULL);
cout << "Listener socket created." << endl;
writeFile << "Listener socket created. - " << asctime(localtime(&t)) << endl;
setsockopt(listenerSock, SOL_SOCKET, SO_REUSEADDR, 0, 0);
/*Bind address to listener socker*/
returnCode = bind(listenerSock, server->ai_addr, (int)server->ai_addrlen);
if (returnCode == SOCKET_ERROR) {
t = time(NULL);
cout << "Failed to bind address to listener port. Error code: " << WSAGetLastError() << " Closing application." << endl;
writeFile << "Failed to bind address to listener port. Error code: " << WSAGetLastError() << " Closing application. - " << asctime(localtime(&t)) << endl;
writeFile.close();
freeaddrinfo(server);
closesocket(listenerSock);
WSACleanup();
return 1;
}
t = time(NULL);
cout << "Address bound to listener socket." << endl;
writeFile << "Address bound to listener socket. - " << asctime(localtime(&t)) << endl;
/*Listen for inbound connections*/
t = time(NULL);
cout << "Listening for connections." << endl;
writeFile << "Listening for connections. - " << asctime(localtime(&t)) << endl;
listen(listenerSock, SOMAXCONN);
}
}
/*Clean up*/
closesocket(listenerSock);
for (int i = 0; i < settings.maxPlayers; i++) {
clientThreads[i].detach();
closesocket(clients[i].socket);
}
WSACleanup();
t = time(NULL);
cout << "Server closed successfully." << endl;
writeFile << "Server closed successfully. - " << asctime(localtime(&t)) << endl;
writeFile.close();
return 0;
}
void clientProcess(client& thisClient, serverSettings& settings) {
int returnCode, loopCount = 0, pingResponse[3] = { 0, 0, 0 };
string message = "";
char returnMessage[defaultBufferLen];
boolean cont = true;
time_t currentTime, previousTime;
previousTime = time(NULL);
while (cont) {
memset(returnMessage, 0, defaultBufferLen);
currentTime = time(NULL);
message = "";
if (currentTime - previousTime == 5) {
/*If 5 seconds has passed send a message and loop for a reply of PING (this is a very basic ping system)*/
if (thisClient.isRunning) {
if (connectedClients < settings.minPlayers) {
message = "Waiting for players. " + to_string(settings.minPlayers - connectedClients) + " more players needed to start.";
returnCode = send(thisClient.socket, message.c_str(), strlen(message.c_str()), 0);
}
else {
message = "Now playing " + gamemodeNames[settings.gamemode - 1] + " on " + mapNames[settings.map - 1]
+ ". Difficulty: " + difficultyNames[settings.difficulty - 1];
returnCode = send(thisClient.socket, message.c_str(), strlen(message.c_str()), 0);
}
}
else {
message = "Spectating " + gamemodeNames[settings.gamemode - 1] + " on " + mapNames[settings.map - 1]
+ ". Difficulty: " + difficultyNames[settings.difficulty - 1];
returnCode = send(thisClient.socket, message.c_str(), strlen(message.c_str()), 0);
}
returnCode = recv(thisClient.socket, returnMessage, defaultBufferLen, 0);
if (returnCode != SOCKET_ERROR) {
if (strcmp(returnMessage, "PING") == 0) {
pingResponse[loopCount] = 1;
}
else {
pingResponse[loopCount] = 0;
}
}
else {
pingResponse[loopCount] = 0;
}
if (pingResponse[0] == 0 && pingResponse[1] == 0 && pingResponse[2] == 0) {
/*No response for 15 seconds - Assume client is dead*/
cont = false;
}
previousTime = currentTime;
cout << "Message sent to client number " << thisClient.ID << endl;
cout << "Client number " << thisClient.ID << " pingResponse[" << loopCount << "] = " << pingResponse[loopCount] << endl;
loopCount++;
if (loopCount == 3) {
loopCount = 0;
}
}
}
/*Loop is only exited if client has disconnected*/
if (thisClient.isRunning) {
currentPlayers--;
}
t = time(NULL);
connectedClients--;
cout << "Client " << thisClient.ID << " has disconnected." << endl;
writeFile << "Client " << thisClient.ID << " has disconnected. - " << asctime(localtime(&t)) << endl;
shutdown(thisClient.socket, 2);
closesocket(thisClient.socket);
thisClient.socket = INVALID_SOCKET;
thisClient.ID = -1;
}
/*
Funtion name - serverSettings()
Parameters - serverSD* settings, string array gamemodeNames, string array mapNames, string array difficultyNames
Returns - serverSD structure (serverSetupDetails -- Stores game rule details in one place)
Functionality -
Take a valid serverSD
Prompt user for setup info
Validate user input
Add valid values to serverSD
Created - Jack Walker
Date - 25/03/2020
*/
void serverSetup(serverSettings* temp) {
int validationLoopCount;
cout << "Server Config" << endl;
/*Gamemode input validation*/
validationLoopCount = 0;
do {
if (validationLoopCount > 0) {
cin.clear();
cin.ignore(1000, '\n');
}
temp->gamemode = 0;
cout << "Please select a gamemode from the following list." << endl;
cout << "1 - " << gamemodeNames[0] << endl;
cout << "2 - " << gamemodeNames[1] << endl;
cout << "3 - " << gamemodeNames[2] << endl;
cout << "Numerical ID of gamemode: ";
cin >> temp->gamemode;
validationLoopCount++;
} while (temp->gamemode < 1 || temp->gamemode > 3);
/*Map input validation*/
validationLoopCount = 0;
do {
if (validationLoopCount > 0) {
cin.clear();
cin.ignore(1000, '\n');
}
temp->map = 0;
cout << "Please select a map from the following list." << endl;
cout << "1 - " << mapNames[0] << endl;
cout << "2 - " << mapNames[1] << endl;
cout << "3 - " << mapNames[2] << endl;
cout << "Numerical ID of map: ";
cin >> temp->map;
validationLoopCount++;
} while (temp->map < 1 || temp->map > 3);
/*Difficulty input validation*/
validationLoopCount = 0;
do {
if (validationLoopCount > 0) {
cin.clear();
cin.ignore(1000, '\n');
}
temp->difficulty = 0;
cout << "Please select a difficulty from the following list." << endl;
cout << "1 - " << difficultyNames[0] << endl;
cout << "2 - " << difficultyNames[1] << endl;
cout << "3 - " << difficultyNames[2] << endl;
cout << "Numerical ID of difficulty: ";
cin >> temp->difficulty;
validationLoopCount++;
} while (temp->difficulty < 1 || temp->difficulty > 3);
/*Minimum players input validation*/
/*NOTE - Minimum players must be 2 or more*/
validationLoopCount = 0;
do {
if (validationLoopCount > 0) {
cin.clear();
cin.ignore(1000, '\n');
}
temp->minPlayers = 0;
cout << "Minimum players (must be 2 or more): ";
cin >> temp->minPlayers;
validationLoopCount++;
} while (temp->minPlayers < 2);
/*Maximum players input validation*/
/*NOTE - Maximum players must be larger than or equal to minimum players*/
validationLoopCount = 0;
do {
if (validationLoopCount > 0) {
cin.clear();
cin.ignore(1000, '\n');
}
temp->maxPlayers = 0;
cout << "Maximum players (must be " << temp->minPlayers << " or more): ";
cin >> temp->maxPlayers;
validationLoopCount++;
} while (temp->maxPlayers < temp->minPlayers);
/*Maximum connections input validation*/
/*NOTE - Maximum connections must be larger than or equal to maximum players*/
validationLoopCount = 0;
do {
if (validationLoopCount > 0) {
cin.clear();
cin.ignore(1000, '\n');
}
temp->maxConnections = 0;
cout << "Maximum connections (must be " << temp->maxPlayers << " or more): ";
cin >> temp->maxConnections;
validationLoopCount++;
} while (temp->maxConnections < temp->maxPlayers);
}