65 lines
1.6 KiB
C
65 lines
1.6 KiB
C
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <atomic>
|
||
|
|
#include <functional>
|
||
|
|
#include <map>
|
||
|
|
#include <mutex>
|
||
|
|
#include <string>
|
||
|
|
#include <thread>
|
||
|
|
#include <vector>
|
||
|
|
|
||
|
|
#include "logger.h"
|
||
|
|
|
||
|
|
class TcpServer
|
||
|
|
{
|
||
|
|
public:
|
||
|
|
struct ClientInfo
|
||
|
|
{
|
||
|
|
int fd;
|
||
|
|
std::string ip;
|
||
|
|
int port;
|
||
|
|
};
|
||
|
|
|
||
|
|
using ReceiveCallback = std::function<void(const std::vector<uint8_t> &)>;
|
||
|
|
using ReceiveStringCallback = std::function<void(const std::string &)>;
|
||
|
|
using StatusCallback = std::function<void(int client_fd, bool connected, const std::string &ip, int port)>;
|
||
|
|
|
||
|
|
TcpServer(const std::string &id, const std::string &ip, int port, Logger &logger);
|
||
|
|
~TcpServer();
|
||
|
|
|
||
|
|
void start();
|
||
|
|
void stop();
|
||
|
|
|
||
|
|
bool send_data(int client_fd, const std::string &data);
|
||
|
|
void broadcast(const std::string &data);
|
||
|
|
|
||
|
|
void set_receive_callback(ReceiveCallback cb) { receive_callback_ = cb; }
|
||
|
|
void set_receive_callback(ReceiveStringCallback cb)
|
||
|
|
{
|
||
|
|
receive_callback_ = [cb](const std::vector<uint8_t> &data) { cb(std::string(data.begin(), data.end())); };
|
||
|
|
}
|
||
|
|
|
||
|
|
void set_status_callback(StatusCallback cb) { status_callback_ = cb; }
|
||
|
|
|
||
|
|
private:
|
||
|
|
void server_loop();
|
||
|
|
void handle_client(ClientInfo client);
|
||
|
|
void close_client(int client_fd);
|
||
|
|
|
||
|
|
private:
|
||
|
|
std::string id_;
|
||
|
|
std::string ip_;
|
||
|
|
int port_;
|
||
|
|
int listen_fd_ = -1;
|
||
|
|
|
||
|
|
std::atomic<bool> running_{false};
|
||
|
|
std::thread worker_;
|
||
|
|
|
||
|
|
std::mutex clients_mutex_;
|
||
|
|
std::map<int, ClientInfo> clients_;
|
||
|
|
|
||
|
|
ReceiveCallback receive_callback_;
|
||
|
|
StatusCallback status_callback_;
|
||
|
|
Logger &logger_;
|
||
|
|
};
|