55 lines
1.4 KiB
C++
55 lines
1.4 KiB
C++
#pragma once
|
|
|
|
#include "util.h"
|
|
#include <asio.hpp>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <of_util.h>
|
|
|
|
using namespace ofen;
|
|
using ExFun_t = std::function<void(CFrameBuffer* buf)>;
|
|
class CTcpServer
|
|
{
|
|
public:
|
|
CTcpServer(asio::io_context& io_context, const std::shared_ptr<spdlog::logger>& logger);
|
|
~CTcpServer();
|
|
|
|
public:
|
|
bool Start(unsigned short port);
|
|
void Stop();
|
|
|
|
private:
|
|
void Accept();
|
|
void HandleClient(std::shared_ptr<asio::ip::tcp::socket> socket, const std::string& client_key);
|
|
|
|
private:
|
|
asio::io_context& io_context_;
|
|
asio::ip::tcp::acceptor acceptor_;
|
|
std::shared_ptr<spdlog::logger> logger_;
|
|
std::map<std::string, int> client_map_;
|
|
std::map<std::string, std::thread> client_threads_;
|
|
std::mutex mutex_;
|
|
};
|
|
|
|
class CTcpClient : public std::enable_shared_from_this<CTcpClient>
|
|
{
|
|
public:
|
|
CTcpClient(asio::io_context& io_context, const std::shared_ptr<spdlog::logger>& logger);
|
|
~CTcpClient();
|
|
|
|
public:
|
|
bool connect(const std::string& host, const std::string& port);
|
|
void disconnect();
|
|
bool send(const char* data, int len);
|
|
void register_func(ExFun_t&& f);
|
|
void async_recv();
|
|
|
|
private:
|
|
std::shared_ptr<spdlog::logger> logger_;
|
|
asio::io_context& io_context_;
|
|
asio::ip::tcp::socket socket_;
|
|
std::mutex mutex_;
|
|
CMutBuffer buffer_;
|
|
std::array<char, 1024> tmp_buf_;
|
|
ExFun_t fun_;
|
|
}; |