geekbrains_network_programming/lesson_04/server/tcp_server.hpp

54 lines
1.1 KiB
C++
Raw Normal View History

2022-09-20 13:37:06 +00:00
/*
2022-09-21 13:04:06 +00:00
* tcp_server.hpp
2022-09-20 13:37:06 +00:00
*
* Created on: 20 сент. 2022 г.
* Author: alexander
*/
#pragma once
#include <boost/asio.hpp>
2022-09-21 13:04:06 +00:00
#include <connection/tcp_connection.hpp>
#include <vector>
2022-09-21 06:57:37 +00:00
#include <optional>
#include <unordered_set>
2022-09-20 13:37:06 +00:00
namespace azh
{
2022-09-21 06:57:37 +00:00
namespace io = boost::asio;
2022-09-20 13:37:06 +00:00
enum class IPV
{
V4, V6
};
class TCPServer
{
2022-09-21 13:04:06 +00:00
using OnJoinHandler = std::function<void(TCPConnection::Pointer)>;
using OnLeaveHandler = std::function<void(TCPConnection::Pointer)>;
using OnClientMessageHandler = std::function<void(std::string)>;
2022-09-20 13:37:06 +00:00
public:
TCPServer(IPV ipv, int port);
2022-09-20 13:37:06 +00:00
int run();
2022-09-21 06:57:37 +00:00
void broadcast(const std::string& message);
2022-09-21 13:04:06 +00:00
public:
OnJoinHandler onJoin;
OnLeaveHandler onLeave;
OnClientMessageHandler onClientMessage;
2022-09-20 13:37:06 +00:00
private:
IPV _ipVersion;
int _port;
2022-09-21 06:57:37 +00:00
io::io_context _ioContext;
io::ip::tcp::acceptor _acceptor;
std::optional<io::ip::tcp::socket> _socket;
2022-09-21 13:04:06 +00:00
std::unordered_set<TCPConnection::Pointer> _connections;
2022-09-20 13:37:06 +00:00
private:
void startAccept();
};
}