libevent学习笔记 ---- 回显服务器 (3)

时间:2021-05-17 00:18:40
在libevent库中提供了evconnlistener系列函数接口,让我们更容易的去监听和建立TCP链接。下面就是使用evconnlistener来构建 的一个高级点的回显服务器。老规矩,废话少说,直接上代码。至于客户端代码可以参考第一篇。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>

#define MAX_BUF_SIZE 1024

void do_event_cb(struct bufferevent *bev, short event, void *arg)
{
if (event & BEV_EVENT_EOF)
{
printf("connection closed by peer, socket: %d ...\r\n",
bufferevent_getfd(bev));
}
else if (event & BEV_EVENT_ERROR)
{
printf("some error happened ...\r\n");
}

bufferevent_free(bev);
}

void do_read_cb(struct bufferevent *bev, void *arg)
{
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
int len = evbuffer_get_length(input);
if (len)
{
evbuffer_add_buffer(output, input);
}
}

void do_accept_cb(struct evconnlistener *listener, int fd,
struct sockaddr *address, int socklen, void *arg)
{
struct event_base *base = evconnlistener_get_base(listener);
struct bufferevent *bev = bufferevent_socket_new(base, fd,
BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, do_read_cb, NULL, do_event_cb, arg);
bufferevent_enable(bev, EV_READ | EV_PERSIST);
}

int init_echo_server(int port)
{
struct evconnlistener *listener;

struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(port);

struct event_base *base = event_base_new();
listener = evconnlistener_new_bind(base, do_accept_cb, NULL,
LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
(struct sockaddr*)&sin, sizeof(sin));
if (!listener)
{
fprintf(stderr, "evconnlistener_new_bind() error ...\r\n");
return -1;
}

event_base_dispatch(base);
event_base_free(base);
return 0;
}

int main(int argc, char **argv)
{
int port = 9999;

if (argc >= 2)
{
port = atoi(argv[1]);
if (port < 0 || port > 65535)
{
fprintf(stderr, "Invalid port ...\r\n");
return -1;
}
}

init_echo_server(port);

return 0;
}