-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_server.cpp
More file actions
69 lines (61 loc) · 1.99 KB
/
Copy pathtcp_server.cpp
File metadata and controls
69 lines (61 loc) · 1.99 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
#include <server/tcp_server.h>
namespace Deadpool
{
TCPServer::TCPServer(IPV ipv, int port) :
_ipv(ipv),
_port(port),
_acceptor(boost::asio::ip::tcp::acceptor(_ioContext, boost::asio::ip::tcp::endpoint(_ipv == IPV::v4 ?
boost::asio::ip::tcp::v4() :
boost::asio::ip::tcp::v6()
, _port)))
{
}
int TCPServer::run()
{
try
{
startAccepting();
std::cout << "Running server on port #" << _port << "..." << std::endl;
_ioContext.run();
}
catch (std::exception& e)
{
std::cerr << "Error!" << std::endl << e.what() << std::endl;
return -1;
}
return 0;
}
void TCPServer::broadcast(const std::string& message)
{
for (const TCPConnection::pointer& connection: _connections)
{
connection->post(message);
}
}
void TCPServer::startAccepting()
{
_socket.emplace(_ioContext);
_acceptor.async_accept(*_socket, [this](const boost::system::error_code& error){
std::shared_ptr<TCPConnection> connection = TCPConnection::create(std::move(*_socket));
std::cout << connection->getAddress() << " has joined the party!" << std::endl;
this->_connections.insert(connection);
if (!error)
{
connection->start(
[this](const std::string& message)
{
broadcast(message);
},
[&, weak = std::weak_ptr(connection)]()
{
if (auto shared = weak.lock(); shared && this->_connections.erase(shared))
{
std::cout << shared->getAddress() << " has left the chat..." << std::endl;
}
}
);
}
this->startAccepting();
});
}
}