51 lines
1.2 KiB
C++
51 lines
1.2 KiB
C++
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <string>
|
||
|
|
#include <functional>
|
||
|
|
#include <thread>
|
||
|
|
#include <atomic>
|
||
|
|
#include <mutex>
|
||
|
|
#include <vector>
|
||
|
|
|
||
|
|
#include "protocol_codec.hpp"
|
||
|
|
#include "mqtt_client_wrapper.hpp"
|
||
|
|
|
||
|
|
class TcpClient
|
||
|
|
{
|
||
|
|
public:
|
||
|
|
using ReceiveCallback = std::function<void(const std::string &data)>;
|
||
|
|
using StatusCallback = std::function<void(bool connected)>;
|
||
|
|
|
||
|
|
TcpClient(const std::string &id, const std::string &ip, int port);
|
||
|
|
~TcpClient();
|
||
|
|
|
||
|
|
void start(); // 启动连接与接收线程
|
||
|
|
void stop(); // 停止连接并关闭 socket
|
||
|
|
bool send_data(const std::string &data); // 发送数据(线程安全)
|
||
|
|
|
||
|
|
void set_receive_callback(ReceiveCallback cb);
|
||
|
|
void set_status_callback(StatusCallback cb);
|
||
|
|
|
||
|
|
bool is_connected() const;
|
||
|
|
|
||
|
|
private:
|
||
|
|
void client_loop(); // 主循环:连接、接收、重连
|
||
|
|
bool try_connect(); // 建立连接
|
||
|
|
void close_socket(); // 关闭连接
|
||
|
|
|
||
|
|
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_;
|
||
|
|
};
|