基于bufferevent epoll tcp客户端代码:
include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
void read_terminal(int fd, short what, void * arg)
{
char buf[1024] = {0};
int len = read(fd, buf, sizeof(buf));
struct bufferevent* bev = (struct bufferevent *) arg;
bufferevent_write(bev, buf, len+1);
}
void read_cb(struct bufferevent * bev, void * arg)
{
char buf[1024] = {0};
int len = bufferevent_read(bev, buf, sizeof(buf));
printf(“recv data: %s\n”, buf);
// bufferevent_write(bev, buf, len+1);
printf(“data have send out…\n”);
}
void write_cb(struct bufferevent * bev, void * arg)
{
printf(“client write_cb is called”);
}
void event_cb(struct bufferevent * bev, short events, void * arg)
{
if(events & BEV_EVENT_EOF) {printf(“connection closed\n”);}
else if(events & BEV_EVENT_ERROR) {printf(“some other error\n”);}
else if(events & BEV_EVENT_CONNECTED) {printf(“have connected to server\n”);return;}
bufferevent_free(bev);
}
int main(int argc, const char * argv[])
{
struct event_base* base = event_base_new();
struct sockaddr_in serv;
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(8787);
inet_pton(AF_INET, "192.168.0.188", &serv.sin_addr.s_addr);
int fd = socket(AF_INET, SOCK_STREAM, 0);
struct bufferevent * bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_socket_connect(bev, (struct sockaddr*)&serv, sizeof(serv));
bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL);
bufferevent_enable(bev, EV_READ);
struct event* ev = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST, read_terminal,bev);
event_add(ev, NULL);
event_base_dispatch(base);
event_base_free(base);
return 0;
}
编译时注意事项:
把libevent.so动态库路径放到环境变量中
export LD_LIBARY_PATH=/usr/local/lib
编译时要带上链接库-levent(libevent.so)
gcc bufferevent_epoll_tcp_server.c -o server -levent