libevent c语言实现 tcp/ip客户端和服务端通信
时间: 2023-08-01 20:11:10 浏览: 287
libevent写的客户端+服务端TCP通信程序源码,具有分包功能
要使用libevent库实现TCP/IP客户端和服务端通信,可以按照以下步骤进行:
1. 引入libevent库的头文件和链接库。
```c
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <fcntl.h>
#pragma comment(lib, "event.lib")
#pragma comment(lib, "event_core.lib")
#pragma comment(lib, "event_extra.lib")
```
2. 创建服务端监听器并设置回调函数。
```c
struct event_base* base = event_base_new(); // 创建event_base对象
// 创建监听器
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(8888);
struct evconnlistener* listener = evconnlistener_new_bind(base, accept_cb, NULL, LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, 10, (struct sockaddr*)&sin, sizeof(sin));
// 设置回调函数
void accept_cb(struct evconnlistener* listener, evutil_socket_t fd, struct sockaddr* addr, int len, void* ptr) {
struct event_base* base = evconnlistener_get_base(listener);
struct bufferevent* bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, read_cb, NULL, event_cb, NULL);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
```
3. 创建客户端并连接到服务端。
```c
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr);
// 创建事件对象
struct event_base* base = event_base_new();
struct bufferevent* bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, read_cb, NULL, event_cb, NULL);
// 连接服务端
bufferevent_socket_connect(bev, (struct sockaddr*)&sin, sizeof(sin));
```
4. 设置读写回调函数。
```c
void read_cb(struct bufferevent* bev, void* ctx) {
struct evbuffer* input = bufferevent_get_input(bev);
size_t len = evbuffer_get_length(input);
char* data = (char*)malloc(len + 1);
memset(data, 0, len + 1);
evbuffer_copyout(input, data, len);
printf("recv: %s\n", data);
free(data);
evbuffer_drain(input, len);
}
void event_cb(struct bufferevent* bev, short events, void* ctx) {
if (events & BEV_EVENT_EOF) {
printf("connection closed\n");
} else if (events & BEV_EVENT_ERROR) {
printf("some other error\n");
}
bufferevent_free(bev);
}
```
5. 启动事件循环。
```c
event_base_dispatch(base);
```
这样就可以使用libevent库实现TCP/IP客户端和服务端通信了。
阅读全文