-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdropboxserver.cpp
88 lines (76 loc) · 2.67 KB
/
dropboxserver.cpp
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
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <cstring>
#include "server.hpp"
#include "udp.hpp"
int main(int argc, char *argv[]){
std::string masterIp;
if (argc < 4) {
std::cout << "Usage:\n\t./udpServer <port> <type: master/slave> <master_port> <ip(if slave)>" << std::endl;
return 0;
}
bool isBackup = false;
int port = atoi(argv[1]);
std::string serverType = argv[2];
int masterPort = atoi(argv[3]);
if (argc == 5){
masterIp = argv[4];
isBackup = true;
}
server_ptr server(new Server);
// if (!isBackup) {
// vlog("Is Master!");
// std::thread masterServer = std::thread(&Server::master, server.get(), masterPort);
// } else {
// vlog("Is Backup!");
// std::thread backupServer = std::thread(&Server::backup, server.get(), masterPort, masterIp);
// }
udpserver_ptr udpserver(new UDPServer(port));
udpserver->_bind();
while(true){
vlog("Server waiting accept");
udpconnection_ptr conn = udpserver->accept(); //wait for new users
vlog("Accept sucess. waiting for username");
conn->recDatagram();
vlog("Got username");
Datagram* userName = conn->getRecvbuffer();
std::string username(userName->data);
user_ptr user;
Datagram response;
auto it = server->getUsers().find(username);
if (it == server->getUsers().end()) {
//IF USER DO NOT EXIST
user_ptr newUser(new User(username));
server->getUsers()[username] = newUser;
response.type = ACCEPT;
conn->sendDatagram(response);
usersession_ptr session(new UserSession(conn, newUser));
newUser->addSession(session);
session->thread = std::thread(&UserSession::runSession, session.get());
} else {
//IF USER EXISTS
user_ptr user(it->second);
if(!user->canConnect()){
//IF USER ALREADY HAS 2 ACTIVE SESSIONS
response.type = REJECT;
conn->sendDatagram(response);
conn->close();
continue;
} else {
//IF USER CAN CONNECT
response.type = ACCEPT;
conn->sendDatagram(response);
usersession_ptr session(new UserSession(conn, user));
user->addSession(session);
session->thread = std::thread(&UserSession::runSession, session.get());
}
}
}
std::cout << "Gracefully exiting?" << std::endl;
return 0;
}