libevent给的例子hello_world.c

时间:2021-02-02 00:18:21
/*
This exmple program provides a trivial server program that listens for TCP
connections on port 9995. When they arrive, it writes a short message to
each client connection, and closes each connection once it is flushed.

Where possible, it exits cleanly in response to a SIGINT (ctrl-c).
*/



#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#ifndef WIN32
#include <netinet/in.h>
# ifdef _XOPEN_SOURCE_EXTENDED
# include <arpa/inet.h>
# endif
#include <sys/socket.h>
#endif

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>
//向每个连接的客户端发送 hello,world
static const char MESSAGE[] = "Hello, World!\n";
//绑定服务端口9995
static const int PORT = 9995;
//客户服务器连接建立后的回调函数
static void listener_cb(struct evconnlistener *, evutil_socket_t,
struct sockaddr *, int socklen, void *);
//向客户写完hello world后的回调函数
static void conn_writecb(struct bufferevent *, void *);
//向客户写入hello world如果发生错误的回调函数
static void conn_eventcb(struct bufferevent *, short, void *);
//监听SIGINT CTRL+C 的回调函数
static void signal_cb(evutil_socket_t, short, void *);

int
main(int argc, char **argv)
{
//可以想象成建立一个epoll模型(or select ...)
struct event_base *base;
//evconnlitener专门用于TCP连接
struct evconnlistener *listener;
//捕获信号的事件
struct event *signal_event;

struct sockaddr_in sin;
#ifdef WIN32
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
//new 一个 epoll
base = event_base_new();
if (!base) {
fprintf(stderr, "Could not initialize libevent!\n");
return 1;
}

memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
//把这个服务地址 端口填好,这个事件绑定到base,回调函数是listener_cb,参数是base。里面的-1表示backlog监听数量。-1就是自动取最合适的值。
listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
(struct sockaddr*)&sin,
sizeof(sin));

if (!listener) {
fprintf(stderr, "Could not create a listener!\n");
return 1;
}
//在dispatch注册捕获函数。捕获信号SIGINT,回调函数signal_cb
signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);

if (!signal_event || event_add(signal_event, NULL)<0) {
fprintf(stderr, "Could not create/add a signal event!\n");
return 1;
}
//let's start loop
event_base_dispatch(base);
//最终释放下列东西。其实服务器会一直loop
evconnlistener_free(listener);
event_free(signal_event);
event_base_free(base);

printf("done\n");
return 0;
}

static void
listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sa, int socklen, void *user_data)
{
struct event_base *base = (event_base *)user_data;
struct bufferevent *bev;
//新建一个buffer,绑定这个base和connfd。BEV_OPT_CLOSE_ON_FREE表示释放 bufferevent 时关闭底层传输端口。
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
if (!bev) {
fprintf(stderr, "Error constructing bufferevent!");
event_base_loopbreak(base);
return;
}
//设置读够,写够,出错的回调函数分别是NULL,conn_writecb,conn_eventcb,传入参数是NULL
bufferevent_setcb(bev, NULL, conn_writecb, conn_eventcb, NULL);
//此buffer允许写
bufferevent_enable(bev, EV_WRITE);
//不允许读
bufferevent_disable(bev, EV_READ);
//向buffer写入hello world。然后调用回调函数conn_writecb,或者出错调用conn_eventcb
//bufferevent_write会自动把output buffer里的数据写到connfd
bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
}

static void
conn_writecb(struct bufferevent *bev, void *user_data)
{
//获取output buffer里的hello world
struct evbuffer *output = bufferevent_get_output(bev);
//如果已经写完数据,就free buffer
if (evbuffer_get_length(output) == 0) {
printf("flushed answer\n");
bufferevent_free(bev);
}
}

static void
conn_eventcb(struct bufferevent *bev, short events, void *user_data)
{
if (events & BEV_EVENT_EOF) {
printf("Connection closed.\n");
} else if (events & BEV_EVENT_ERROR) {
printf("Got an error on the connection: %s\n",
strerror(errno));/*XXX win32*/
}
/* None of the other events can happen here, since we haven't enabled
* timeouts */

bufferevent_free(bev);
}

static void
signal_cb(evutil_socket_t sig, short events, void *user_data)
{
struct event_base *base = (event_base *)user_data;
struct timeval delay = { 2, 0 };

printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
//在给定时间后退出base loop
//event_base_loopbreak()与event_base_loopexit()区别
//前者处理完事件再退出,后者设定时候后退出,如果时间=NULL,马上退出
event_base_loopexit(base, &delay);
}