source: network-game/server/server.cpp@ 15efb4e

Last change on this file since 15efb4e was b8601ee, checked in by dportnoy <dmp1488@…>, 11 years ago

The server keeps track of each team's score and sends SCORE meesages to the clients upon login and when the score changes

  • Property mode set to 100644
File size: 19.7 KB
Line 
1#include <cstdlib>
2#include <cstdio>
3#include <unistd.h>
4#include <string>
5#include <iostream>
6#include <sstream>
7#include <cstring>
8#include <cmath>
9
10#include <vector>
11#include <map>
12
13#include <sys/time.h>
14
15#include <sys/socket.h>
16#include <netdb.h>
17#include <netinet/in.h>
18#include <arpa/inet.h>
19
20#include <crypt.h>
21
22/*
23#include <openssl/bio.h>
24#include <openssl/ssl.h>
25#include <openssl/err.h>
26*/
27
28#include "../common/Compiler.h"
29#include "../common/Common.h"
30#include "../common/Message.h"
31#include "../common/WorldMap.h"
32#include "../common/Player.h"
33
34#include "DataAccess.h"
35
36using namespace std;
37
38// from used to be const. Removed that so I could take a reference
39// and use it to send messages
40bool processMessage(const NETWORK_MSG &clientMsg, struct sockaddr_in &from, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedId, NETWORK_MSG &serverMsg, int sock, int &scoreBlue, int &scoreRed);
41
42void updateUnusedId(unsigned int& id, map<unsigned int, Player>& mapPlayers);
43
44// this should probably go somewhere in the common folder
45void error(const char *msg)
46{
47 perror(msg);
48 exit(0);
49}
50
51Player *findPlayerByName(map<unsigned int, Player> &m, string name)
52{
53 map<unsigned int, Player>::iterator it;
54
55 for (it = m.begin(); it != m.end(); it++)
56 {
57 if ( it->second.name.compare(name) == 0 )
58 return &(it->second);
59 }
60
61 return NULL;
62}
63
64Player *findPlayerByAddr(map<unsigned int, Player> &m, const sockaddr_in &addr)
65{
66 map<unsigned int, Player>::iterator it;
67
68 for (it = m.begin(); it != m.end(); it++)
69 {
70 if ( it->second.addr.sin_addr.s_addr == addr.sin_addr.s_addr &&
71 it->second.addr.sin_port == addr.sin_port )
72 return &(it->second);
73 }
74
75 return NULL;
76}
77
78int main(int argc, char *argv[])
79{
80 int sock, length, n;
81 struct sockaddr_in server;
82 struct sockaddr_in from; // info of client sending the message
83 NETWORK_MSG clientMsg, serverMsg;
84 map<unsigned int, Player> mapPlayers;
85 unsigned int unusedId = 1;
86 int scoreBlue, scoreRed;
87
88 scoreBlue = 0;
89 scoreRed = 0;
90
91 //SSL_load_error_strings();
92 //ERR_load_BIO_strings();
93 //OpenSSL_add_all_algorithms();
94
95 if (argc < 2) {
96 cerr << "ERROR, no port provided" << endl;
97 exit(1);
98 }
99
100 WorldMap* gameMap = WorldMap::loadMapFromFile("../data/map.txt");
101
102 // add some items to the map. They will be sent out
103 // to players when they login
104 for (int y=0; y<gameMap->height; y++) {
105 for (int x=0; x<gameMap->width; x++) {
106 switch (gameMap->getStructure(x, y)) {
107 case WorldMap::STRUCTURE_BLUE_FLAG:
108 gameMap->addObject(WorldMap::OBJECT_BLUE_FLAG, x*25+12, y*25+12);
109 break;
110 case WorldMap::STRUCTURE_RED_FLAG:
111 gameMap->addObject(WorldMap::OBJECT_RED_FLAG, x*25+12, y*25+12);
112 break;
113 }
114 }
115 }
116
117 sock = socket(AF_INET, SOCK_DGRAM, 0);
118 if (sock < 0) error("Opening socket");
119 length = sizeof(server);
120 bzero(&server,length);
121 server.sin_family=AF_INET;
122 server.sin_port=htons(atoi(argv[1]));
123 server.sin_addr.s_addr=INADDR_ANY;
124 if ( bind(sock, (struct sockaddr *)&server, length) < 0 )
125 error("binding");
126
127 set_nonblock(sock);
128
129 bool broadcastResponse;
130 timespec ts;
131 int timeLastUpdated = 0, curTime = 0, timeLastBroadcast = 0;
132 while (true) {
133
134 usleep(5000);
135
136 clock_gettime(CLOCK_REALTIME, &ts);
137 // make the number smaller so millis can fit in an int
138 ts.tv_sec -= 1368000000;
139 curTime = ts.tv_sec*1000 + ts.tv_nsec/1000000;
140
141 if (timeLastUpdated == 0 || (curTime-timeLastUpdated) >= 50) {
142 timeLastUpdated = curTime;
143
144 // maybe put this in a separate method
145 map<unsigned int, Player>::iterator it;
146 FLOAT_POSITION oldPos;
147 bool broadcastMove = false;
148 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
149 oldPos = it->second.pos;
150 if (it->second.move(gameMap)) {
151
152 // check if the move needs to be canceled
153 switch(gameMap->getElement(it->second.pos.x/25, it->second.pos.y/25)) {
154 case WorldMap::TERRAIN_NONE:
155 case WorldMap::TERRAIN_OCEAN:
156 case WorldMap::TERRAIN_ROCK:
157 {
158 it->second.pos = oldPos;
159 it->second.target.x = it->second.pos.x;
160 it->second.target.y = it->second.pos.y;
161 broadcastMove = true;
162 break;
163 }
164 default:
165 // if there are no obstacles, do nothing
166 break;
167 }
168
169 WorldMap::ObjectType flagType;
170 POSITION pos;
171 bool flagTurnedIn = false;
172
173 switch(gameMap->getStructure(it->second.pos.x/25, it->second.pos.y/25)) {
174 case WorldMap::STRUCTURE_BLUE_FLAG:
175 {
176 if (it->second.team == 0 && it->second.hasRedFlag)
177 {
178 it->second.hasRedFlag = false;
179 flagType = WorldMap::OBJECT_RED_FLAG;
180 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
181 flagTurnedIn = true;
182 scoreBlue++;
183 }
184
185 break;
186 }
187 case WorldMap::STRUCTURE_RED_FLAG:
188 {
189 if (it->second.team == 1 && it->second.hasBlueFlag)
190 {
191 it->second.hasBlueFlag = false;
192 flagType = WorldMap::OBJECT_BLUE_FLAG;
193 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
194 flagTurnedIn = true;
195 scoreRed++;
196 }
197
198 break;
199 }
200 }
201
202 if (flagTurnedIn) {
203 // send an OBJECT message to add the flag back to its spawn point
204 pos.x = pos.x*25+12;
205 pos.y = pos.y*25+12;
206 gameMap->addObject(flagType, pos.x, pos.y);
207
208 serverMsg.type = MSG_TYPE_OBJECT;
209 gameMap->getObjects()->back().serialize(serverMsg.buffer);
210
211 map<unsigned int, Player>::iterator it2;
212 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
213 {
214 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
215 error("sendMessage");
216 }
217
218 serverMsg.type = MSG_TYPE_SCORE;
219 memcpy(serverMsg.buffer, &scoreBlue, 4);
220 memcpy(serverMsg.buffer+4, &scoreRed, 4);
221
222 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
223 {
224 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
225 error("sendMessage");
226 }
227
228 // this means a PLAYER message will be sent
229 broadcastMove = true;
230 }
231
232 if (broadcastMove) {
233 serverMsg.type = MSG_TYPE_PLAYER;
234 it->second.serialize(serverMsg.buffer);
235
236 cout << "about to broadcast move" << endl;
237 map<unsigned int, Player>::iterator it2;
238 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
239 {
240 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
241 error("sendMessage");
242 }
243 }
244 }
245 }
246 }
247
248 n = receiveMessage(&clientMsg, sock, &from);
249
250 if (n >= 0) {
251 broadcastResponse = processMessage(clientMsg, from, mapPlayers, gameMap, unusedId, serverMsg, sock, scoreBlue, scoreRed);
252
253 // probably replace this with a function that prints based on the
254 // message type
255 cout << "msg: " << serverMsg.buffer << endl;
256 if (broadcastResponse)
257 {
258 cout << "Should be broadcasting the message" << endl;
259
260 map<unsigned int, Player>::iterator it;
261 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
262 {
263 cout << "Sent message back to " << it->second.name << endl;
264 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
265 error("sendMessage");
266 }
267 }
268 else
269 {
270 cout << "Should be sending back the message" << endl;
271
272 if ( sendMessage(&serverMsg, sock, &from) < 0 )
273 error("sendMessage");
274 }
275 }
276 }
277
278 return 0;
279}
280
281bool processMessage(const NETWORK_MSG& clientMsg, struct sockaddr_in& from, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedId, NETWORK_MSG& serverMsg, int sock, int &scoreBlue, int &scoreRed)
282{
283 DataAccess da;
284
285 cout << "Received message" << endl;
286 cout << "MSG: type: " << clientMsg.type << endl;
287 cout << "MSG contents: " << clientMsg.buffer << endl;
288
289 // maybe we should make a message class and have this be a member
290 bool broadcastResponse = false;
291
292 // Check that if an invalid message is sent, the client will correctly
293 // receive and display the response. Maybe make a special error msg type
294 switch(clientMsg.type)
295 {
296 case MSG_TYPE_REGISTER:
297 {
298 string username(clientMsg.buffer);
299 string password(strchr(clientMsg.buffer, '\0')+1);
300
301 cout << "username: " << username << endl;
302 cout << "password: " << password << endl;
303
304 int error = da.insertPlayer(username, password);
305
306 if (!error)
307 strcpy(serverMsg.buffer, "Registration successful.");
308 else
309 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
310
311 serverMsg.type = MSG_TYPE_REGISTER;
312
313 break;
314 }
315 case MSG_TYPE_LOGIN:
316 {
317 cout << "Got login message" << endl;
318
319 serverMsg.type = MSG_TYPE_LOGIN;
320
321 string username(clientMsg.buffer);
322 string password(strchr(clientMsg.buffer, '\0')+1);
323
324 Player* p = da.getPlayer(username);
325
326 if (p == NULL || !da.verifyPassword(password, p->password))
327 {
328 strcpy(serverMsg.buffer, "Incorrect username or password");
329 }
330 else if(findPlayerByName(mapPlayers, username) != NULL)
331 {
332 strcpy(serverMsg.buffer, "Player has already logged in.");
333 }
334 else
335 {
336 serverMsg.type = MSG_TYPE_PLAYER;
337
338 updateUnusedId(unusedId, mapPlayers);
339 p->id = unusedId;
340 cout << "new player id: " << p->id << endl;
341 p->setAddr(from);
342
343 // choose a random team (either 0 or 1)
344 p->team = rand() % 2;
345
346 // tell the new player about all the existing players
347 cout << "Sending other players to new player" << endl;
348
349 map<unsigned int, Player>::iterator it;
350 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
351 {
352 it->second.serialize(serverMsg.buffer);
353
354 cout << "sending info about " << it->second.name << endl;
355 cout << "sending id " << it->second.id << endl;
356 if ( sendMessage(&serverMsg, sock, &from) < 0 )
357 error("sendMessage");
358 }
359
360 // tell the new player about all map objects
361 // (currently just the flags)
362 serverMsg.type = MSG_TYPE_OBJECT;
363 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
364 vector<WorldMap::Object>::iterator itObjects;
365 cout << "sending items" << endl;
366 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
367 itObjects->serialize(serverMsg.buffer);
368 cout << "sending item id " << itObjects->id << endl;
369 if ( sendMessage(&serverMsg, sock, &from) < 0 )
370 error("sendMessage");
371 }
372
373 // send the current score
374 serverMsg.type = MSG_TYPE_SCORE;
375 memcpy(serverMsg.buffer, &scoreBlue, 4);
376 memcpy(serverMsg.buffer+4, &scoreRed, 4);
377 if ( sendMessage(&serverMsg, sock, &from) < 0 )
378 error("sendMessage");
379
380 serverMsg.type = MSG_TYPE_PLAYER;
381 p->serialize(serverMsg.buffer);
382 cout << "Should be broadcasting the message" << endl;
383
384 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
385 {
386 cout << "Sent message back to " << it->second.name << endl;
387 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
388 error("sendMessage");
389 }
390
391 serverMsg.type = MSG_TYPE_LOGIN;
392 mapPlayers[unusedId] = *p;
393 }
394
395 delete(p);
396
397 break;
398 }
399 case MSG_TYPE_LOGOUT:
400 {
401 string name(clientMsg.buffer);
402 cout << "Player logging out: " << name << endl;
403
404 Player *p = findPlayerByName(mapPlayers, name);
405
406 if (p == NULL)
407 {
408 strcpy(serverMsg.buffer, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
409 cout << "Player not logged in" << endl;
410 }
411 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
412 p->addr.sin_port != from.sin_port )
413 {
414 strcpy(serverMsg.buffer, "That player is logged in using a differemt connection. This is either a bug, or you're trying to hack the server.");
415 cout << "Player logged in using a different connection" << endl;
416 }
417 else
418 {
419 if (p->id < unusedId)
420 unusedId = p->id;
421 mapPlayers.erase(p->id);
422 strcpy(serverMsg.buffer, "You have successfully logged out.");
423 }
424
425 serverMsg.type = MSG_TYPE_LOGOUT;
426
427 break;
428 }
429 case MSG_TYPE_CHAT:
430 {
431 cout << "Got a chat message" << endl;
432
433 Player *p = findPlayerByAddr(mapPlayers, from);
434
435 if (p == NULL)
436 {
437 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
438 }
439 else
440 {
441 broadcastResponse = true;
442
443 ostringstream oss;
444 oss << p->name << ": " << clientMsg.buffer;
445
446 strcpy(serverMsg.buffer, oss.str().c_str());
447 }
448
449 serverMsg.type = MSG_TYPE_CHAT;
450
451 break;
452 }
453 case MSG_TYPE_PLAYER_MOVE:
454 {
455 cout << "PLAYER_MOVE" << endl;
456
457 int id, x, y;
458
459 memcpy(&id, clientMsg.buffer, 4);
460 memcpy(&x, clientMsg.buffer+4, 4);
461 memcpy(&y, clientMsg.buffer+8, 4);
462
463 cout << "x: " << x << endl;
464 cout << "y: " << y << endl;
465 cout << "id: " << id << endl;
466
467 if ( mapPlayers[id].addr.sin_addr.s_addr == from.sin_addr.s_addr &&
468 mapPlayers[id].addr.sin_port == from.sin_port )
469 {
470 // we need to make sure the player can move here
471 if (0 <= x && x < 300 && 0 <= y && y < 300 &&
472 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
473 {
474 cout << "valid terrain" << endl;
475
476 mapPlayers[id].target.x = x;
477 mapPlayers[id].target.y = y;
478
479 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
480
481 memcpy(serverMsg.buffer, &id, 4);
482 memcpy(serverMsg.buffer+4, &mapPlayers[id].target.x, 4);
483 memcpy(serverMsg.buffer+8, &mapPlayers[id].target.y, 4);
484
485 broadcastResponse = true;
486 }
487 else
488 cout << "Bad terrain detected" << endl;
489 }
490 else // nned to send back a message indicating failure
491 cout << "Player id (" << id << ") doesn't match sender" << endl;
492
493 break;
494 }
495 case MSG_TYPE_PICKUP_FLAG:
496 {
497 // may want to check the id matches the sender, just like for PLAYER_NOVE
498 cout << "PICKUP_FLAG" << endl;
499
500 int id;
501
502 memcpy(&id, clientMsg.buffer, 4);
503 cout << "id: " << id << endl;
504
505 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
506 vector<WorldMap::Object>::iterator itObjects;
507
508 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end();) {
509 POSITION pos = itObjects->pos;
510 bool gotFlag = false;
511
512 if (posDistance(mapPlayers[id].pos, pos.toFloat()) < 10) {
513 switch (itObjects->type) {
514 case WorldMap::OBJECT_BLUE_FLAG:
515 if (mapPlayers[id].team == 1) {
516 gotFlag = true;
517 mapPlayers[id].hasBlueFlag = true;
518 broadcastResponse = true;
519 }
520 break;
521 case WorldMap::OBJECT_RED_FLAG:
522 if (mapPlayers[id].team == 0) {
523 gotFlag = true;
524 mapPlayers[id].hasRedFlag = true;
525 broadcastResponse = true;
526 }
527 break;
528 }
529
530 if (gotFlag) {
531 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
532 memcpy(serverMsg.buffer, &itObjects->id, 4);
533
534 map<unsigned int, Player>::iterator it;
535 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
536 {
537 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
538 error("sendMessage");
539 }
540
541 // remove the object from the server-side map
542 cout << "size before: " << gameMap->getObjects()->size() << endl;
543 itObjects = vctObjects->erase(itObjects);
544 cout << "size after: " << gameMap->getObjects()->size() << endl;
545 }
546 }
547
548 if (!gotFlag)
549 itObjects++;
550 }
551
552 serverMsg.type = MSG_TYPE_PLAYER;
553 mapPlayers[id].serialize(serverMsg.buffer);
554
555 break;
556 }
557 case MSG_TYPE_DROP_FLAG:
558 {
559 // may want to check the id matches the sender, just like for PLAYER_NOVE
560 cout << "DROP_FLAG" << endl;
561
562 int id;
563
564 memcpy(&id, clientMsg.buffer, 4);
565 cout << "id: " << id << endl;
566
567 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
568 if (mapPlayers[id].hasBlueFlag)
569 flagType = WorldMap::OBJECT_BLUE_FLAG;
570 else if (mapPlayers[id].hasRedFlag)
571 flagType = WorldMap::OBJECT_RED_FLAG;
572
573 gameMap->addObject(flagType, mapPlayers[id].pos.x, mapPlayers[id].pos.y);
574
575 // need to send the OBJECT message too
576 serverMsg.type = MSG_TYPE_OBJECT;
577 gameMap->getObjects()->back().serialize(serverMsg.buffer);
578
579 map<unsigned int, Player>::iterator it;
580 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
581 {
582 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
583 error("sendMessage");
584 }
585
586 mapPlayers[id].hasBlueFlag = false;
587 mapPlayers[id].hasRedFlag = false;
588
589 serverMsg.type = MSG_TYPE_PLAYER;
590 mapPlayers[id].serialize(serverMsg.buffer);
591
592 map<unsigned int, Player>::iterator it2;
593 broadcastResponse = true;
594
595 break;
596 }
597 default:
598 {
599 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
600
601 serverMsg.type = MSG_TYPE_CHAT;
602
603 break;
604 }
605 }
606
607 return broadcastResponse;
608}
609
610void updateUnusedId(unsigned int& id, map<unsigned int, Player>& mapPlayers)
611{
612 while (mapPlayers.find(id) != mapPlayers.end())
613 id++;
614}
Note: See TracBrowser for help on using the repository browser.