-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserversocket.cpp
More file actions
82 lines (72 loc) · 2.34 KB
/
serversocket.cpp
File metadata and controls
82 lines (72 loc) · 2.34 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
#include "serversocket.h"
#include "supertcpmanager.h"
#include <algorithm>
void ServerSocket::send(const std::string &message)
{
for (auto it = clientSockets.begin(); it != clientSockets.end(); it++)
{
(*it)->send(message);
}
}
ServerSocket::ServerSocket(int sockfd, SuperTcpManager &manager, std::function<void(ClientSocket *)> newConnection)
: AbstractSocket(sockfd, manager),
newConnection(newConnection)
{
SuperTcpManager::printMyDebug("Server constructor", sockfd);
tcpManager.addSocket(sockfd, [&](epoll_event ev)
{
if ((ev.events & EPOLLERR) ||
(ev.events & EPOLLHUP))
{
return;
}
auto portFd = ev.data.fd;
SuperTcpManager::printMyDebug("input connection on", portFd);
while (true)
{
sockaddr in_addr;
socklen_t in_len = sizeof (struct sockaddr);
int infd = accept(portFd, &in_addr, &in_len);
if (infd == -1)
{
break;
}
SuperTcpManager::makeSocketNonBlocking(infd);
SuperTcpManager::printMyDebug("get accept on: ", infd);
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
int s = getnameinfo(&in_addr, in_len,
hbuf, sizeof hbuf,
sbuf, sizeof sbuf,
NI_NUMERICHOST | NI_NUMERICSERV);
if (s == 0)
{
SuperTcpManager::printMyDebug("Accepted connection desc =", infd, "host = ", hbuf, "port = ", sbuf);
this->clientSockets.push_back(std::unique_ptr<ClientSocket>(new ClientSocket(infd, this->tcpManager, this)));
this->newConnection((this->clientSockets.back().get()));
}
}
});
}
void ServerSocket::removeClient(ClientSocket* client)
{
auto it = std::find_if(clientSockets.begin(), clientSockets.end(), [client](const std::unique_ptr<ClientSocket>& p)
{
return client == p.get();
});
if (it != clientSockets.end())
{
clientSockets.erase(it);
}
}
ServerSocket::~ServerSocket()
{
SuperTcpManager::printMyDebug("Server destructor", sockfd);
while (!clientSockets.empty())
{
clientSockets.pop_back();
}
}
void ServerSocket::close()
{
tcpManager.removeSocket(this);
}