基于bufferevent epoll tcp服务器代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.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};
bufferevent_read(bev, buf, sizeof(buf));
printf(“recv data : %s\n”, buf);
char* ptr = "have received client data\n";
// bufferevent_write(bev, ptr, strlen(ptr)+1);
// printf("have send out data\n");
}
void write_cb(struct bufferevent * bev, void* arg)
{
printf(“data have been send out\n”);
}
void event_cb(struct bufferevent * bev, short events, void* arg)
{
if(events & BEV_EVENT_EOF){ printf(“connecte closed\n”);}
else if(events & BEV_EVENT_ERROR) {printf(“some other error\n”);}
bufferevent_free(bev);
}
void listen_cb(struct evconnlistener* listener, evutil_socket_t fd,struct sockaddr addr, int len, void ptr)
{
struct event_base * base = (struct event_base )ptr;
struct bufferevent bev = NULL;
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
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);
}
int main(int argc, const char* arg[])
{
//
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(8989);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
struct evconnlistener* listen = NULL;
listen = evconnlistener_new_bind(base, listen_cb, base,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
-1, (struct sockaddr*)&serv, sizeof(serv));
event_base_dispatch(base);
evconnlistener_free(listen);
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