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

Last change on this file since b81cea1 was 23559e7, checked in by dportnoy <dmp1488@…>, 12 years ago

Move player interaction with objects on the map from Player::move to the server

  • Property mode set to 100644
File size: 14.1 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 switch(gameMap->getStructure(it->second.pos.x/25, it->second.pos.y/25)) {
164 case WorldMap::STRUCTURE_BLUE_FLAG:
165 cout << "Got blue flag" << endl;
166 it->second.hasBlueFlag = true;
167 broadcastMove = true;
168 break;
169 case WorldMap::STRUCTURE_RED_FLAG:
170 cout << "Got red flag" << endl;
171 it->second.hasRedFlag = true;
172 broadcastMove = true;
173 break;
174 }
175
176 if (broadcastMove) {
177 serverMsg.type = MSG_TYPE_PLAYER;
178 it->second.serialize(serverMsg.buffer);
179
180 cout << "about to broadcast move" << endl;
181 map<unsigned int, Player>::iterator it, it2;
182 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
183 {
184 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
185 error("sendMessage");
186 }
187 }
188 }
189 }
190 }
191
192 n = receiveMessage(&clientMsg, sock, &from);
193
194 if (n >= 0) {
195 cout << "Got a message" << endl;
196
197 broadcastResponse = processMessage(clientMsg, from, mapPlayers, gameMap, unusedId, serverMsg, sock);
198
199 // probably replace this with a function that prints based on the
200 // message type
201 cout << "msg: " << serverMsg.buffer << endl;
202 cout << "broadcastResponse: " << broadcastResponse << endl;
203 if (broadcastResponse)
204 {
205 cout << "Should be broadcasting the message" << endl;
206
207 map<unsigned int, Player>::iterator it;
208 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
209 {
210 cout << "Sent message back to " << it->second.name << endl;
211 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
212 error("sendMessage");
213 }
214 }
215 else
216 {
217 cout << "Should be sending back the message" << endl;
218
219 if ( sendMessage(&serverMsg, sock, &from) < 0 )
220 error("sendMessage");
221 }
222 }
223 }
224
225 return 0;
226}
227
228bool processMessage(const NETWORK_MSG& clientMsg, struct sockaddr_in& from, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedId, NETWORK_MSG& serverMsg, int sock)
229{
230 DataAccess da;
231
232 cout << "MSG: type: " << clientMsg.type << endl;
233 cout << "MSG contents: " << clientMsg.buffer << endl;
234
235 // maybe we should make a message class and have this be a member
236 bool broadcastResponse = false;
237
238 // Check that if an invalid message is sent, the client will correctly
239 // receive and display the response. Maybe make a special error msg type
240 switch(clientMsg.type)
241 {
242 case MSG_TYPE_REGISTER:
243 {
244 string username(clientMsg.buffer);
245 string password(strchr(clientMsg.buffer, '\0')+1);
246
247 cout << "username: " << username << endl;
248 cout << "password: " << password << endl;
249
250 int error = da.insertPlayer(username, password);
251
252 if (!error)
253 strcpy(serverMsg.buffer, "Registration successful.");
254 else
255 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
256
257 serverMsg.type = MSG_TYPE_REGISTER;
258
259 break;
260 }
261 case MSG_TYPE_LOGIN:
262 {
263 cout << "Got login message" << endl;
264
265 serverMsg.type = MSG_TYPE_LOGIN;
266
267 string username(clientMsg.buffer);
268 string password(strchr(clientMsg.buffer, '\0')+1);
269
270 Player* p = da.getPlayer(username);
271
272 if (p == NULL || !da.verifyPassword(password, p->password))
273 {
274 strcpy(serverMsg.buffer, "Incorrect username or password");
275 }
276 else if(findPlayerByName(mapPlayers, username) != NULL)
277 {
278 strcpy(serverMsg.buffer, "Player has already logged in.");
279 }
280 else
281 {
282 serverMsg.type = MSG_TYPE_PLAYER;
283
284 p->setAddr(from);
285 updateUnusedId(unusedId, mapPlayers);
286 p->id = unusedId;
287 cout << "new player id: " << p->id << endl;
288
289 // tell the new player about all the existing players
290 cout << "Sending other players to new player" << endl;
291
292 map<unsigned int, Player>::iterator it;
293 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
294 {
295 it->second.serialize(serverMsg.buffer);
296
297 cout << "sending info about " << it->second.name << endl;
298 cout << "sending id " << it->second.id << endl;
299 if ( sendMessage(&serverMsg, sock, &from) < 0 )
300 error("sendMessage");
301 }
302
303 // tell the new player about all map objects
304 // (currently just the flags)
305 serverMsg.type = MSG_TYPE_OBJECT;
306 vector<WorldMap::Object> vctObjects = gameMap->getObjects();
307 vector<WorldMap::Object>::iterator itObjects;
308 cout << "sending items" << endl;
309 for (itObjects = vctObjects.begin(); itObjects != vctObjects.end(); itObjects++) {
310 itObjects->serialize(serverMsg.buffer);
311 cout << "sending item id " << itObjects->id << endl;
312 if ( sendMessage(&serverMsg, sock, &from) < 0 )
313 error("sendMessage");
314 }
315
316 p->serialize(serverMsg.buffer);
317 cout << "Should be broadcasting the message" << endl;
318
319 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
320 {
321 cout << "Sent message back to " << it->second.name << endl;
322 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
323 error("sendMessage");
324 }
325
326 serverMsg.type = MSG_TYPE_LOGIN;
327 mapPlayers[unusedId] = *p;
328 }
329
330 delete(p);
331
332 break;
333 }
334 case MSG_TYPE_LOGOUT:
335 {
336 string name(clientMsg.buffer);
337 cout << "Player logging out: " << name << endl;
338
339 Player *p = findPlayerByName(mapPlayers, name);
340
341 if (p == NULL)
342 {
343 strcpy(serverMsg.buffer, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
344 cout << "Player not logged in" << endl;
345 }
346 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
347 p->addr.sin_port != from.sin_port )
348 {
349 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.");
350 cout << "Player logged in using a different connection" << endl;
351 }
352 else
353 {
354 if (p->id < unusedId)
355 unusedId = p->id;
356 mapPlayers.erase(p->id);
357 strcpy(serverMsg.buffer, "You have successfully logged out.");
358 cout << "Player logged out successfuly" << endl;
359 }
360
361 serverMsg.type = MSG_TYPE_LOGOUT;
362
363 break;
364 }
365 case MSG_TYPE_CHAT:
366 {
367 cout << "Got a chat message" << endl;
368
369 Player *p = findPlayerByAddr(mapPlayers, from);
370
371 if (p == NULL)
372 {
373 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
374 }
375 else
376 {
377 broadcastResponse = true;
378
379 ostringstream oss;
380 oss << p->name << ": " << clientMsg.buffer;
381
382 strcpy(serverMsg.buffer, oss.str().c_str());
383 }
384
385 serverMsg.type = MSG_TYPE_CHAT;
386
387 break;
388 }
389 case MSG_TYPE_PLAYER_MOVE:
390 {
391 istringstream iss;
392 iss.str(clientMsg.buffer);
393
394 cout << "PLAYER_MOVE" << endl;
395
396 int id, x, y;
397
398 memcpy(&id, clientMsg.buffer, 4);
399 memcpy(&x, clientMsg.buffer+4, 4);
400 memcpy(&y, clientMsg.buffer+8, 4);
401
402 cout << "x: " << x << endl;
403 cout << "y: " << y << endl;
404 cout << "id: " << id << endl;
405
406 if ( mapPlayers[id].addr.sin_addr.s_addr == from.sin_addr.s_addr &&
407 mapPlayers[id].addr.sin_port == from.sin_port )
408 {
409 // we need to make sure the player can move here
410 if (0 <= x && x < 300 && 0 <= y && y < 300 &&
411 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
412 {
413 cout << "valid terrain" << endl;
414
415 mapPlayers[id].target.x = x;
416 mapPlayers[id].target.y = y;
417 int xDiff = mapPlayers[id].target.x - mapPlayers[id].pos.x;
418 int yDiff = mapPlayers[id].target.y - mapPlayers[id].pos.y;
419
420 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
421
422 memcpy(serverMsg.buffer, &id, 4);
423 memcpy(serverMsg.buffer+4, &mapPlayers[id].target.x, 4);
424 memcpy(serverMsg.buffer+8, &mapPlayers[id].target.y, 4);
425
426 broadcastResponse = true;
427 }
428 else
429 cout << "Bad terrain detected" << endl;
430 }
431 else // nned to send back a message indicating failure
432 cout << "Player id (" << id << ") doesn't match sender" << endl;
433
434 break;
435 }
436 default:
437 {
438 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
439
440 serverMsg.type = MSG_TYPE_CHAT;
441
442 break;
443 }
444 }
445
446 cout << "Got to the end of the switch" << endl;
447
448 return broadcastResponse;
449}
450
451void updateUnusedId(unsigned int& id, map<unsigned int, Player>& mapPlayers)
452{
453 while (mapPlayers.find(id) != mapPlayers.end())
454 id++;
455}
Note: See TracBrowser for help on using the repository browser.