-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.cpp
More file actions
92 lines (79 loc) · 1.41 KB
/
input.cpp
File metadata and controls
92 lines (79 loc) · 1.41 KB
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
#include "Server.hpp"
void Server::cleanupUser(int fd)
{
map<int, User>::iterator it = getUserFD(fd);
if (it != _users.end())
disconnectUser(it->second);
else
removeConnection(fd);
}
void cleanNewlines(string &acc)
{
while (acc.find("\r\n") != std::string::npos)
acc.replace(acc.find("\r\n"), 2, "\n");
}
bool hasNewline(string &acc)
{
size_t newline = acc.find("\n");
return (newline != std::string::npos);
}
string extractCmd(string &acc)
{
size_t newline = acc.find("\n");
string cmd = acc.substr(0, newline);
acc.erase(0, newline + 1);
return (cmd);
}
bool hasEOF(string &acc)
{
size_t eof = acc.find(EOF);
return (eof != std::string::npos);
}
void rmEOF(string &acc)
{
size_t eof = acc.find(EOF);
acc.erase(eof);
}
string getCommand(User &u)
{
string cmd;
string &acc = u._cmdAcc;
cleanNewlines(acc);
if (hasNewline(acc))
{
string cmd = extractCmd(acc);
return (cmd);
}
if (hasEOF(acc))
rmEOF(acc);
return ("");
}
void Server::processCommands(User &u)
{
string cmd;
while(1)
{
cmd = getCommand(u);
if (cmd.empty())
break;
Command c(cmd);
executeCommand(u, c);
}
}
void Server::receiveInput(int fd)
{
char buf[8912];
int received;
memset(buf, 0, 8192);
received = recv(fd, buf, 8192, 0);
if (received == -1)
throw readingMsgFailed();
else if (received == 0)
cleanupUser(fd);
else
{
User &u = getUserFD(fd)->second;
u.appendAcc(buf);
processCommands(u);
}
}