| 1 |
TCP 客户端类 |
| 2 |
|
| 3 |
```c++ |
| 4 |
|
| 5 |
class TcpClient { |
| 6 |
|
| 7 |
// 返回所在的事件循环 |
| 8 |
const EventLoopPtr& loop(); |
| 9 |
|
| 10 |
// 创建套接字 |
| 11 |
int createsocket(int remote_port, const char* remote_host = "127.0.0.1"); |
| 12 |
int createsocket(struct sockaddr* remote_addr); |
| 13 |
|
| 14 |
// 绑定端口 |
| 15 |
int bind(int local_port, const char* local_host = "0.0.0.0"); |
| 16 |
int bind(struct sockaddr* local_addr); |
| 17 |
|
| 18 |
// 关闭套接字 |
| 19 |
void closesocket(); |
| 20 |
|
| 21 |
// 开始运行 |
| 22 |
void start(bool wait_threads_started = true); |
| 23 |
|
| 24 |
// 停止运行 |
| 25 |
void stop(bool wait_threads_stopped = true); |
| 26 |
|
| 27 |
// 是否已连接 |
| 28 |
bool isConnected(); |
| 29 |
|
| 30 |
// 发送 |
| 31 |
int send(const void* data, int size); |
| 32 |
int send(Buffer* buf); |
| 33 |
int send(const std::string& str); |
| 34 |
|
| 35 |
// 设置SSL/TLS加密通信 |
| 36 |
int withTLS(hssl_ctx_opt_t* opt = NULL); |
| 37 |
|
| 38 |
// 设置连接超时 |
| 39 |
void setConnectTimeout(int ms); |
| 40 |
|
| 41 |
// 设置重连 |
| 42 |
void setReconnect(reconn_setting_t* setting); |
| 43 |
|
| 44 |
// 是否是重连 |
| 45 |
bool isReconnect(); |
| 46 |
|
| 47 |
// 设置拆包规则 |
| 48 |
void setUnpack(unpack_setting_t* setting); |
| 49 |
|
| 50 |
// 连接状态回调 |
| 51 |
std::function<void(const TSocketChannelPtr&)> onConnection; |
| 52 |
|
| 53 |
// 消息回调 |
| 54 |
std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage; |
| 55 |
|
| 56 |
// 写完成回调 |
| 57 |
std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete; |
| 58 |
|
| 59 |
}; |
| 60 |
|
| 61 |
``` |
| 62 |
|
| 63 |
测试代码见 [evpp/TcpClient_test.cpp](../../evpp/TcpClient_test.cpp) |