55 lines
1.4 KiB
C++
55 lines
1.4 KiB
C++
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <string>
|
||
|
|
#include <thread>
|
||
|
|
#include <mutex>
|
||
|
|
#include <atomic>
|
||
|
|
#include <map>
|
||
|
|
#include <functional>
|
||
|
|
#include <vector>
|
||
|
|
|
||
|
|
class TcpServer
|
||
|
|
{
|
||
|
|
public:
|
||
|
|
struct ClientInfo
|
||
|
|
{
|
||
|
|
int fd;
|
||
|
|
std::string ip;
|
||
|
|
int port;
|
||
|
|
};
|
||
|
|
|
||
|
|
using ReceiveCallback = std::function<void(int client_fd, const std::string &data)>;
|
||
|
|
using StatusCallback = std::function<void(int client_fd, bool connected, const std::string &ip, int port)>;
|
||
|
|
|
||
|
|
TcpServer(const std::string &ip, int port);
|
||
|
|
~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);
|
||
|
|
void set_status_callback(StatusCallback cb);
|
||
|
|
|
||
|
|
private:
|
||
|
|
void server_loop(); // 主监听线程
|
||
|
|
void client_handler(ClientInfo client); // 客户端线程
|
||
|
|
void close_client(int client_fd); // 关闭指定客户端
|
||
|
|
|
||
|
|
private:
|
||
|
|
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_; // fd -> info
|
||
|
|
|
||
|
|
ReceiveCallback receive_callback_;
|
||
|
|
StatusCallback status_callback_;
|
||
|
|
};
|