基于libevent实现tcp客户端及服务端
时间: 2024-09-14 15:09:00 浏览: 68
基于libevent库实现TCP客户端和服务端主要是利用其异步事件处理机制,简化网络编程的复杂性。libevent是一个高效的、跨平台的事件驱动框架,特别适合用于实时应用和网络服务器。
**TCP客户端示例**:
```cpp
#include <event2/event.h>
void on_connect(struct evconnbase *cb, short revents) {
if (revents & EV_ERROR) {
perror("Connect failed");
return;
}
struct sockaddr_in server_addr;
// ...填充服务器地址...
int fd = accept(cb->ev_base->fd, (struct sockaddr *)&server_addr, NULL);
if (fd == -1) {
perror("Accept failed");
return;
}
event_set(&client_event, fd, EV_READ | EV_PERSIST, on_read, cb);
event_add(&client_event, NULL);
}
void on_read(struct evconnbase *cb, short revents) {
if (revents & EV_TIMEOUT) {
fprintf(stderr, "Read timeout\n");
return;
}
char buf[1024];
ssize_t n = read(cb->fd, buf, sizeof(buf));
if (n <= 0) {
if (n == 0)
printf("Connection closed by peer\n");
else
perror("Read error");
event_del(&client_event);
} else {
// 发送响应或数据处理
}
}
int main() {
// 初始化libevent
event_init();
// 创建连接事件
struct event_base *base = event_base_new();
struct evconnbase *client_event = evconnbase_new(base, on_connect);
// 连接服务器,设置超时等
// ...实际连接过程...
// 主循环
while (1) {
event_base_dispatch(base);
}
event_base_free(base);
event_system_exit(0);
}
```
**TCP服务端示例**:
```cpp
void on_connection(struct evconnbase *cb, short revents) {
if (revents & EV_ERROR) {
perror("Connection failed");
return;
}
struct sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
int fd = accept(cb->ev_base->fd, (struct sockaddr *)&client_addr, &addr_len);
if (fd == -1) {
perror("Accept failed");
return;
阅读全文