source: network-game/server/server.cpp@ df79cfd

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

The server assigns a random team to each player when they login

  • Property mode set to 100644
File size: 16.3 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);
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
87 //SSL_load_error_strings();
88 //ERR_load_BIO_strings();
89 //OpenSSL_add_all_algorithms();
90
91 if (argc < 2) {
92 cerr << "ERROR, no port provided" << endl;
93 exit(1);
94 }
95
96 WorldMap* gameMap = WorldMap::loadMapFromFile("../data/map.txt");
97
98 // add some items to the map. They will be sent out
99 // to players when they login
100 for (int y=0; y<gameMap->height; y++) {
101 for (int x=0; x<gameMap->width; x++) {
102 switch (gameMap->getStructure(x, y)) {
103 case WorldMap::STRUCTURE_BLUE_FLAG:
104 gameMap->addObject(WorldMap::OBJECT_BLUE_FLAG, x*25+12, y*25+12);
105 break;
106 case WorldMap::STRUCTURE_RED_FLAG:
107 gameMap->addObject(WorldMap::OBJECT_RED_FLAG, x*25+12, y*25+12);
108 break;
109 }
110 }
111 }
112
113 sock = socket(AF_INET, SOCK_DGRAM, 0);
114 if (sock < 0) error("Opening socket");
115 length = sizeof(server);
116 bzero(&server,length);
117 server.sin_family=AF_INET;
118 server.sin_port=htons(atoi(argv[1]));
119 server.sin_addr.s_addr=INADDR_ANY;
120 if ( bind(sock, (struct sockaddr *)&server, length) < 0 )
121 error("binding");
122
123 set_nonblock(sock);
124
125 bool broadcastResponse;
126 timespec ts;
127 int timeLastUpdated = 0, curTime = 0, timeLastBroadcast = 0;
128 while (true) {
129
130 usleep(5000);
131
132 clock_gettime(CLOCK_REALTIME, &ts);
133 // make the number smaller so millis can fit in an int
134 ts.tv_sec -= 1368000000;
135 curTime = ts.tv_sec*1000 + ts.tv_nsec/1000000;
136
137 if (timeLastUpdated == 0 || (curTime-timeLastUpdated) >= 50) {
138 timeLastUpdated = curTime;
139
140 // maybe put this in a separate method
141 map<unsigned int, Player>::iterator it;
142 FLOAT_POSITION oldPos;
143 bool broadcastMove = false;
144 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
145 oldPos = it->second.pos;
146 if (it->second.move(gameMap)) {
147
148 // check if the move needs to be canceled
149 switch(gameMap->getElement(it->second.pos.x/25, it->second.pos.y/25)) {
150 case WorldMap::TERRAIN_NONE:
151 case WorldMap::TERRAIN_OCEAN:
152 case WorldMap::TERRAIN_ROCK:
153 it->second.pos = oldPos;
154 it->second.target.x = it->second.pos.x;
155 it->second.target.y = it->second.pos.y;
156 broadcastMove = true;
157 break;
158 default:
159 // if there are no obstacles, do nothing
160 break;
161 }
162
163 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
164 vector<WorldMap::Object>::iterator itObjects;
165
166 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end();) {
167 POSITION pos = itObjects->pos;
168 if (posDistance(it->second.pos, pos.toFloat()) < 10) {
169 switch (itObjects->type) {
170 case WorldMap::OBJECT_BLUE_FLAG:
171 cout << "Got blue flag" << endl;
172 it->second.hasBlueFlag = true;
173 broadcastMove = true;
174 break;
175 case WorldMap::OBJECT_RED_FLAG:
176 cout << "Got red flag" << endl;
177 it->second.hasRedFlag = true;
178 broadcastMove = true;
179 break;
180 }
181
182 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
183 memcpy(serverMsg.buffer, &itObjects->id, 4);
184
185 map<unsigned int, Player>::iterator it2;
186 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
187 {
188 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
189 error("sendMessage");
190 }
191
192 // remove the object from the server-side map
193 cout << "size before: " << gameMap->getObjects()->size() << endl;
194 itObjects = vctObjects->erase(itObjects);
195 cout << "size after: " << gameMap->getObjects()->size() << endl;
196 }
197 else
198 itObjects++;
199 }
200
201 if (broadcastMove) {
202 serverMsg.type = MSG_TYPE_PLAYER;
203 it->second.serialize(serverMsg.buffer);
204
205 cout << "about to broadcast move" << endl;
206 map<unsigned int, Player>::iterator it2;
207 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
208 {
209 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
210 error("sendMessage");
211 }
212 }
213 }
214 }
215 }
216
217 n = receiveMessage(&clientMsg, sock, &from);
218
219 if (n >= 0) {
220 broadcastResponse = processMessage(clientMsg, from, mapPlayers, gameMap, unusedId, serverMsg, sock);
221
222 // probably replace this with a function that prints based on the
223 // message type
224 cout << "msg: " << serverMsg.buffer << endl;
225 if (broadcastResponse)
226 {
227 cout << "Should be broadcasting the message" << endl;
228
229 map<unsigned int, Player>::iterator it;
230 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
231 {
232 cout << "Sent message back to " << it->second.name << endl;
233 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
234 error("sendMessage");
235 }
236 }
237 else
238 {
239 cout << "Should be sending back the message" << endl;
240
241 if ( sendMessage(&serverMsg, sock, &from) < 0 )
242 error("sendMessage");
243 }
244 }
245 }
246
247 return 0;
248}
249
250bool processMessage(const NETWORK_MSG& clientMsg, struct sockaddr_in& from, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedId, NETWORK_MSG& serverMsg, int sock)
251{
252 DataAccess da;
253
254 cout << "Received message" << endl;
255 cout << "MSG: type: " << clientMsg.type << endl;
256 cout << "MSG contents: " << clientMsg.buffer << endl;
257
258 // maybe we should make a message class and have this be a member
259 bool broadcastResponse = false;
260
261 // Check that if an invalid message is sent, the client will correctly
262 // receive and display the response. Maybe make a special error msg type
263 switch(clientMsg.type)
264 {
265 case MSG_TYPE_REGISTER:
266 {
267 string username(clientMsg.buffer);
268 string password(strchr(clientMsg.buffer, '\0')+1);
269
270 cout << "username: " << username << endl;
271 cout << "password: " << password << endl;
272
273 int error = da.insertPlayer(username, password);
274
275 if (!error)
276 strcpy(serverMsg.buffer, "Registration successful.");
277 else
278 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
279
280 serverMsg.type = MSG_TYPE_REGISTER;
281
282 break;
283 }
284 case MSG_TYPE_LOGIN:
285 {
286 cout << "Got login message" << endl;
287
288 serverMsg.type = MSG_TYPE_LOGIN;
289
290 string username(clientMsg.buffer);
291 string password(strchr(clientMsg.buffer, '\0')+1);
292
293 Player* p = da.getPlayer(username);
294
295 if (p == NULL || !da.verifyPassword(password, p->password))
296 {
297 strcpy(serverMsg.buffer, "Incorrect username or password");
298 }
299 else if(findPlayerByName(mapPlayers, username) != NULL)
300 {
301 strcpy(serverMsg.buffer, "Player has already logged in.");
302 }
303 else
304 {
305 serverMsg.type = MSG_TYPE_PLAYER;
306
307 updateUnusedId(unusedId, mapPlayers);
308 p->id = unusedId;
309 cout << "new player id: " << p->id << endl;
310 p->setAddr(from);
311
312 // choose a random team (either 0 or 1)
313 p->team = rand() % 2;
314
315 // tell the new player about all the existing players
316 cout << "Sending other players to new player" << endl;
317
318 map<unsigned int, Player>::iterator it;
319 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
320 {
321 it->second.serialize(serverMsg.buffer);
322
323 cout << "sending info about " << it->second.name << endl;
324 cout << "sending id " << it->second.id << endl;
325 if ( sendMessage(&serverMsg, sock, &from) < 0 )
326 error("sendMessage");
327 }
328
329 // tell the new player about all map objects
330 // (currently just the flags)
331 serverMsg.type = MSG_TYPE_OBJECT;
332 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
333 vector<WorldMap::Object>::iterator itObjects;
334 cout << "sending items" << endl;
335 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
336 itObjects->serialize(serverMsg.buffer);
337 cout << "sending item id " << itObjects->id << endl;
338 if ( sendMessage(&serverMsg, sock, &from) < 0 )
339 error("sendMessage");
340 }
341
342 p->serialize(serverMsg.buffer);
343 cout << "Should be broadcasting the message" << endl;
344
345 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
346 {
347 cout << "Sent message back to " << it->second.name << endl;
348 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
349 error("sendMessage");
350 }
351
352 serverMsg.type = MSG_TYPE_LOGIN;
353 mapPlayers[unusedId] = *p;
354 }
355
356 delete(p);
357
358 break;
359 }
360 case MSG_TYPE_LOGOUT:
361 {
362 string name(clientMsg.buffer);
363 cout << "Player logging out: " << name << endl;
364
365 Player *p = findPlayerByName(mapPlayers, name);
366
367 if (p == NULL)
368 {
369 strcpy(serverMsg.buffer, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
370 cout << "Player not logged in" << endl;
371 }
372 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
373 p->addr.sin_port != from.sin_port )
374 {
375 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.");
376 cout << "Player logged in using a different connection" << endl;
377 }
378 else
379 {
380 if (p->id < unusedId)
381 unusedId = p->id;
382 mapPlayers.erase(p->id);
383 strcpy(serverMsg.buffer, "You have successfully logged out.");
384 }
385
386 serverMsg.type = MSG_TYPE_LOGOUT;
387
388 break;
389 }
390 case MSG_TYPE_CHAT:
391 {
392 cout << "Got a chat message" << endl;
393
394 Player *p = findPlayerByAddr(mapPlayers, from);
395
396 if (p == NULL)
397 {
398 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
399 }
400 else
401 {
402 broadcastResponse = true;
403
404 ostringstream oss;
405 oss << p->name << ": " << clientMsg.buffer;
406
407 strcpy(serverMsg.buffer, oss.str().c_str());
408 }
409
410 serverMsg.type = MSG_TYPE_CHAT;
411
412 break;
413 }
414 case MSG_TYPE_PLAYER_MOVE:
415 {
416 cout << "PLAYER_MOVE" << endl;
417
418 int id, x, y;
419
420 memcpy(&id, clientMsg.buffer, 4);
421 memcpy(&x, clientMsg.buffer+4, 4);
422 memcpy(&y, clientMsg.buffer+8, 4);
423
424 cout << "x: " << x << endl;
425 cout << "y: " << y << endl;
426 cout << "id: " << id << endl;
427
428 if ( mapPlayers[id].addr.sin_addr.s_addr == from.sin_addr.s_addr &&
429 mapPlayers[id].addr.sin_port == from.sin_port )
430 {
431 // we need to make sure the player can move here
432 if (0 <= x && x < 300 && 0 <= y && y < 300 &&
433 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
434 {
435 cout << "valid terrain" << endl;
436
437 mapPlayers[id].target.x = x;
438 mapPlayers[id].target.y = y;
439
440 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
441
442 memcpy(serverMsg.buffer, &id, 4);
443 memcpy(serverMsg.buffer+4, &mapPlayers[id].target.x, 4);
444 memcpy(serverMsg.buffer+8, &mapPlayers[id].target.y, 4);
445
446 broadcastResponse = true;
447 }
448 else
449 cout << "Bad terrain detected" << endl;
450 }
451 else // nned to send back a message indicating failure
452 cout << "Player id (" << id << ") doesn't match sender" << endl;
453
454 break;
455 }
456 case MSG_TYPE_DROP_FLAG:
457 {
458 // may want to check the id matches the sender, just like for PLAYER_NOVE
459 cout << "DROP_FLAG" << endl;
460
461 int id;
462
463 memcpy(&id, clientMsg.buffer, 4);
464 cout << "id: " << id << endl;
465
466 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
467 if (mapPlayers[id].hasBlueFlag)
468 flagType = WorldMap::OBJECT_BLUE_FLAG;
469 else if (mapPlayers[id].hasRedFlag)
470 flagType = WorldMap::OBJECT_RED_FLAG;
471
472 gameMap->addObject(flagType, mapPlayers[id].pos.x, mapPlayers[id].pos.y);
473
474 // need to send the OBJECT message too
475 serverMsg.type = MSG_TYPE_OBJECT;
476 gameMap->getObjects()->back().serialize(serverMsg.buffer);
477
478 map<unsigned int, Player>::iterator it;
479 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
480 {
481 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
482 error("sendMessage");
483 }
484
485 mapPlayers[id].hasBlueFlag = false;
486 mapPlayers[id].hasRedFlag = false;
487
488 serverMsg.type = MSG_TYPE_PLAYER;
489 mapPlayers[id].serialize(serverMsg.buffer);
490
491 map<unsigned int, Player>::iterator it2;
492 broadcastResponse = true;
493
494 break;
495 }
496 default:
497 {
498 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
499
500 serverMsg.type = MSG_TYPE_CHAT;
501
502 break;
503 }
504 }
505
506 return broadcastResponse;
507}
508
509void updateUnusedId(unsigned int& id, map<unsigned int, Player>& mapPlayers)
510{
511 while (mapPlayers.find(id) != mapPlayers.end())
512 id++;
513}
Note: See TracBrowser for help on using the repository browser.