geekbrains_network_programming/lesson_04/server/tcp_server.cpp

74 lines
1.7 KiB
C++
Raw Normal View History

2022-09-20 13:37:06 +00:00
/*
2022-09-21 13:04:06 +00:00
* tcp_server.cpp
2022-09-20 13:37:06 +00:00
*
* Created on: 20 сент. 2022 г.
* Author: alexander
*/
2022-09-21 13:04:06 +00:00
#include <connection/tcp_connection.hpp>
2022-09-20 13:37:06 +00:00
#include <server/tcp_server.hpp>
#include <iostream>
namespace azh
{
using boost::asio::ip::tcp;
TCPServer::TCPServer(IPV ipv, int port) : _ipVersion(ipv), _port(port), _acceptor(_ioContext,
tcp::endpoint(_ipVersion == IPV::V4 ? tcp::v4() : tcp::v6(), _port))
{
}
int TCPServer::run()
{
try
{
startAccept();
_ioContext.run();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
2022-09-21 13:04:06 +00:00
void TCPServer::broadcast(const std::string &message)
2022-09-20 13:37:06 +00:00
{
2022-09-21 13:04:06 +00:00
for (auto &connection : _connections)
{
connection->post(message);
}
2022-09-20 13:37:06 +00:00
}
2022-09-21 06:57:37 +00:00
void TCPServer::startAccept()
{
2022-09-21 06:57:37 +00:00
_socket.emplace(_ioContext);
2022-09-21 06:57:37 +00:00
_acceptor.async_accept(*_socket, [this](const boost::system::error_code &error)
{
2022-09-21 13:04:06 +00:00
auto connection = TCPConnection::create(std::move(*_socket));
if (onJoin)
onJoin(connection);
2022-09-21 06:57:37 +00:00
_connections.insert(connection);
2022-09-21 06:57:37 +00:00
if (!error)
2022-09-21 13:04:06 +00:00
connection->start(
[this](const std::string& message)
{
if (onClientMessage) onClientMessage(message);
},
[&, weak = std::weak_ptr(connection)]
{
if (auto shared = weak.lock(); shared && _connections.erase(shared))
if (onLeave) onLeave(shared);
}
);
2022-09-21 06:57:37 +00:00
startAccept();
});
}
2022-09-20 13:37:06 +00:00
}