Files
CPP_Core/Socket_old/TCP_Client.h
T
2026-06-16 10:56:40 +08:00

48 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
#include "Core/Base/RingBuffer.hpp"
#include "Core/Statistics/Statistics.h"
#include "Socket.h"
#include <atomic>
#include <chrono>
namespace Psc::socket {
class TCP_Client : public Socket_Base {
public:
~TCP_Client() override;
void set_buffer_size(size_t size) { max_buffer_size = size; }
void set_dest_address(const Sockaddr_In& a) { dest_address = a; }
void create();
// 建议:外部周期性调用一次(比如主循环/线程每 1~10ms)
void tick();
std::string read();
void send(const std::string& data);
std::string to_string() override;
enum State {
Not_Created,
Not_Set_Field,
Reconnecting,
Connecting,
Wait_Check,
Connected
};
void close() override;
std::atomic<State> state{Not_Created};
void set_state(State s);
std::function<void(State old_state, State new_state)> on_state_change = nullptr;
Enum_Err<NetError> last_err = Enum_Err(NetError::unknown_error);
protected:
size_t max_buffer_size = 1024 * 1024;
StreamRingBuffer_ST send_buffer;
Sockaddr_In dest_address{};
int reconnect_backoff_ms = 200;
std::chrono::steady_clock::time_point next_reconnect_tp{};
// 内部流程
void schedule_recreate(Enum_Err<NetError> e);
bool start_connect(); // 发起 connect(可能 EINPROGRESS
bool check_writeable(); // EINPROGRESS 后检查是否真连上
void flush_send_buffer(); // 尝试把 ringbuffer 发出去
};
} // namespace Psc::socket