72 lines
1.9 KiB
C++
72 lines
1.9 KiB
C++
#pragma once
|
|
|
|
#include <atomic>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
#include "logger.h"
|
|
|
|
class TcpClient
|
|
{
|
|
public:
|
|
using ReceiveCallback = std::function<void(const std::vector<uint8_t> &)>;
|
|
using ReceiveStringCallback = std::function<void(const std::string &)>;
|
|
using StatusCallback = std::function<void(bool connected)>;
|
|
|
|
TcpClient(const std::string &id, const std::string &ip, int port, Logger &logger);
|
|
~TcpClient();
|
|
|
|
void start(); // 启动连接与接收线程
|
|
void stop(); // 停止连接并关闭 socket
|
|
bool send_data(const std::string &data); // 发送数据(线程安全)
|
|
|
|
void set_receive_callback(ReceiveCallback cb) { receive_callback_ = cb; }
|
|
|
|
// 自动把 vector 转 string 后再回调
|
|
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; }
|
|
|
|
bool is_connected() const;
|
|
|
|
// 设置重连策略,单位秒
|
|
void set_reconnect_policy(int first, int max)
|
|
{
|
|
reconnect_first_ = first;
|
|
reconnect_max_ = max;
|
|
}
|
|
|
|
private:
|
|
void client_loop(); // 主循环:连接、接收、重连
|
|
bool try_connect(); // 建立连接
|
|
void close_socket(); // 关闭连接
|
|
void handle_io(); // 抽取收包逻辑
|
|
|
|
private:
|
|
std::string id_;
|
|
std::string ip_;
|
|
int port_;
|
|
|
|
int sock_fd_ = -1;
|
|
std::atomic<bool> running_{false};
|
|
std::atomic<bool> connected_{false};
|
|
|
|
std::thread worker_;
|
|
std::mutex send_mutex_;
|
|
|
|
ReceiveCallback receive_callback_;
|
|
StatusCallback status_callback_;
|
|
|
|
Logger &logger_;
|
|
|
|
// 重连策略
|
|
int reconnect_first_ = 5; // 初始间隔(秒)
|
|
int reconnect_max_ = 300; // 最大间隔(秒)
|
|
};
|