-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cpp
248 lines (219 loc) · 5.82 KB
/
Server.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#include "Server.h"
Server::Server()
{
WSADATA wsaData;
int retResult;
if (retResult = WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
std::cerr << "WSAStartup failed: " << retResult;
return;
}
//Create server socket
listenSock = Socket::createSocket("10001");
//Set up map of actions. The map uses a string as the key and an
//std::function<Event(string, Client)> as the value
/*actions["/Name"] = std::bind(&Server::changeName, this, std::placeholders::_1, std::placeholders::_2);
actions["/Quit"] = std::bind(&Server::clientExit, this, std::placeholders::_1, std::placeholders::_2);
actions["/Help"] = std::bind(&Server::sendHelpText, this, std::placeholders::_1, std::placeholders::_2);
*/
Actions::setAction("/Name", std::bind(&Server::changeName, this, std::placeholders::_1, std::placeholders::_2));
Actions::setAction("/Quit", std::bind(&Server::clientExit, this, std::placeholders::_1, std::placeholders::_2));
Actions::setAction("/Help", std::bind(&Server::sendHelpText, this, std::placeholders::_1, std::placeholders::_2));
run.store(true);
runThread = std::thread(&Server::update, this);
}
Server::~Server()
{
if(run.load())
{
shutdownServer();
}
}
void Server::update()
{
while(run.load())
{
if(!getNewClient(listenSock))
{
break;
}
}
WSACleanup();
}
void Server::shutdownServer()
{
run.store(false);
for(int i = 0; i < clientThreads.size(); ++i)
{
clientThreads.at(i).join();
}
runThread.join();
}
//Messaging
void Server::broadcast(Message message)
{
std::string mess = getClientIdentifier(message.senderID) + ": " + message.data + "\0";
for(int i = 0; i < clients.size(); i++)
{
if(clients.at(i).id != message.senderID)
{
send(clients.at(i).sock, mess.c_str(), mess.length(), 0);
}
}
}
void Server::whisper(Message message)
{
std::string mess = getClientIdentifier(-1) + ": " + message.data + "\0";
for(int i = 0; i < clients.size(); i++)
{
if(clients.at(i).id == message.senderID)
{
send(clients.at(i).sock, mess.c_str(), mess.length(), 0);
break;
}
}
}
//Client handlers
void Server::handleClient(Client client)
{
std::string message = "";
bool success = true;
Actions::Event event = Actions::Event::ENTER;
while(success && event != Actions::Event::QUIT && run.load())
{
message = "";
success = Socket::listenTo(client.sock, message);
if(success)
{
std::cout << getClientIdentifier(client.id) << ": " << message << std::endl;
event = handleMessage(message, client);
}
}
//Shutdown client socket
//Shutdown sending data (from client's perspective)
if (shutdown(client.sock, SD_SEND) == SOCKET_ERROR)
{
std::cerr << "shutdown() failed: " << WSAGetLastError() << std::endl;
closesocket(client.sock);
WSACleanup();
//Remove client from list of clients
for(int i = 0; i < clients.size(); ++i)
{
if(clients.at(i).id == client.id)
{
clients.erase(clients.begin() + i);
break;
}
}
return;
}
//Shutdown recieving data (from client's perspective)
closesocket(client.sock);
//Remove client from list of clients
for(int i = 0; i < clients.size(); ++i)
{
if(clients.at(i).id == client.id)
{
clients.erase(clients.begin() + i);
break;
}
}
}
bool Server::getNewClient(SOCKET toListen)
{
//Listen on a socket
if (listen(toListen, SOMAXCONN) == SOCKET_ERROR)
{
std::cerr << "Listen failed with error: " << WSAGetLastError();
closesocket(toListen);
WSACleanup();
return false;
}
//Accept a connection
SOCKET clientSock = INVALID_SOCKET;
fd_set readFD, writeFD, exceptFD;
FD_ZERO(&readFD);
FD_SET(toListen, &readFD);
struct timeval tv = {0, 0};
//If there is something waiting on the socket in the next [timeval] seconds, check that it's an incoming connection then accept it
if(select(0, &readFD, NULL, NULL, &tv) > 0)
{
if(FD_ISSET(toListen, &readFD))
{
clientSock = accept(toListen, NULL, NULL);
if (clientSock == INVALID_SOCKET)
{
std::cerr << "accept() failed: " << WSAGetLastError();
closesocket(toListen);
WSACleanup();
return false;
}
Client newCli = Client("", ticketNumber++, clientSock);
clients.push_back(newCli);
clientThreads.push_back(std::thread(&Server::handleClient, this, newCli));
return true;
}
}
return true;
}
std::string Server::getClientIdentifier(int clientID)
{
for(Client cli : clients)
{
if(cli.id == clientID)
{
if(!cli.name.empty())
{
return cli.name;
}else
{
return std::to_string(clientID);
}
}
}
return "Server";
}
//Event handlers
Actions::Event Server::changeName(std::string message, Client client)
{
for(int i = 0; i < clients.size(); i++)
{
if(clients.at(i).id == client.id)
{
//Position 5 should be the beginning of the next word after "/Name"
clients.at(i).name = message.substr(6, std::string::npos);
std::string shout = "[" + std::to_string(clients.at(i).id) + "] has changed their name to " + clients.at(i).name;
broadcast(Message(shout, -1));
return Actions::Event::NAME;
}
}
return Actions::Event::SPEAK;
}
Actions::Event Server::clientExit(std::string message, Client client)
{
broadcast(Message(getClientIdentifier(client.id) + " has left.", -1));
return Actions::Event::QUIT;
}
Actions::Event Server::sendHelpText(std::string message, Client client)
{
std::string helpText = "Welcome to the server. There are several commands that you can use.\n/Name [NewName here] changes your name\n/Quit to exit\n/Help to see this help text";
whisper(Message(helpText, client.id));
return Actions::Event::HELP;
}
Actions::Event Server::handleMessage(std::string message, Client client)
{
/*for(auto val : actions)
{
if(message.find(val.first) != std::string::npos)
{
return val.second(message, client);
}
}*/
auto func = Actions::getAction(message);
if(func != nullptr)
{
return func(message, client);
}
broadcast(Message(message, client.id));
return Actions::Event::SPEAK;
}