source: network-game/server/server.cpp@ 45b2750

Last change on this file since 45b2750 was 5f868c0, checked in by dportnoy <dmp1488@…>, 12 years ago

Added partial server support for new messages for sending item info

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