c版本
#include "hv/hloop.h"
#include "hv/htime.h"
void on_timer(htimer_t* timer) {
char str[DATETIME_FMT_BUFLEN] = {0};
datetime_t dt = datetime_now();
datetime_fmt(&dt, str);
printf("> %s\n", str);
// 获取userdata
hio_t* io = (hio_t*)hevent_userdata(timer);
// 发送当前时间字符串
hio_write(io, str, strlen(str));
}
void on_close(hio_t* io) {
}
void on_recv(hio_t* io, void* buf, int readbytes) {
printf("< %.*s\n", readbytes, (char*)buf);
}
void on_connect(hio_t* io) {
// 设置read回调
hio_setcb_read(io, on_recv);
// 开始读
hio_read(io);
// 添加一个定时器
htimer_t* timer = htimer_add(hevent_loop(io), on_timer, 1000, INFINITE);
// 设置userdata
hevent_set_userdata(timer, io);
}
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: cmd port\n");
return -10;
}
int port = atoi(argv[1]);
// 创建事件循环
hloop_t* loop = hloop_new(0);
// 创建TCP客户端
hio_t* io = hloop_create_tcp_client(loop, "127.0.0.1", port, on_connect, on_close);
if (io == NULL) {
return -20;
}
// 运行事件循环
hloop_run(loop);
// 释放事件循环
hloop_free(&loop);
return 0;
}
完整TCP/UDP客户端程序可参考examples/nc.c、examples/tcp_client_test.c
c++版本
示例代码见:evpp/TcpClient_test.cpp
#include "hv/TcpClient.h"
#include "hv/htime.h"
using namespace hv;
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s port\n", argv[0]);
return -10;
}
int port = atoi(argv[1]);
TcpClient cli;
int connfd = cli.createsocket(port);
if (connfd < 0) {
return -20;
}
printf("client connect to port %d, connfd=%d ...\n", port, connfd);
cli.onConnection = [](const SocketChannelPtr& channel) {
std::string peeraddr = channel->peeraddr();
if (channel->isConnected()) {
printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
// send(time) every 3s
setInterval(3000, [channel](TimerID timerID){
if (channel->isConnected()) {
char str[DATETIME_FMT_BUFLEN] = {0};
datetime_t dt = datetime_now();
datetime_fmt(&dt, str);
channel->write(str);
} else {
killTimer(timerID);
}
});
} else {
printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
}
};
cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
};
cli.onWriteComplete = [](const SocketChannelPtr& channel, Buffer* buf) {
printf("> %.*s\n", (int)buf->size(), (char*)buf->data());
};
// reconnect: 1,2,4,8,10,10,10...
reconn_setting_t reconn;
reconn_setting_init(&reconn);
reconn.min_delay = 1000;
reconn.max_delay = 10000;
reconn.delay_policy = 2;
cli.setReconnect(&reconn);
cli.start();
// press Enter to stop
while (getchar() != '\n');
return 0;
}
TcpClient
更多实用接口
setConnectTimeout
:设置连接超时setReconnect
:设置重连setUnpack
: 设置拆包withTLS
:SSL/TLS加密通信