首页 > 代码库 > libevent (二) 接收TCP连接

libevent (二) 接收TCP连接

libevent 接收TCP连接

Evconnlistener 机制为您提供了侦听和接受传入的 TCP 连接的方法。下面的函数全部包含在`<event2/listener.h>`中。

evconnlistener

创建监听对象

struct evconnlistener *evconnlistener_new(struct event_base *base,evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,evutil_socket_t fd);struct evconnlistener *evconnlistener_new_bind(struct event_base *base,evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,const struct sockaddr *sa, int socklen);void evconnlistener_free(struct evconnlistener *lev);

两个函数都会申请空间并返回一个新的连接对象`evconnlistener`,其中第一个函数需要自己绑定套接字,而第二个函数会自动绑定套接字。`evconnlistener`根据`event_base`来判断TCP连接请求,每当到来一个请求,它就会调用`evconnlistener_cb`回调函数来处理该请求。`ptr`是回调函数的参数,`backlog`指定了`listen`的个数,而`flag`参数如下:

* LEV_OPT_LEAVE_SOCKETS_BLOCKING 设置阻塞* LEV_OPT_CLOSE_ON_FREE 释放掉 `evconnlistener`会关闭socket* LEV_OPT_CLOSE_ON_EXEC * LEV_OPT_REUSEABLE `socket`重用* LEV_OPT_THREADSAFE 为socket增加锁,用于多线程/多进程操作* LEV_OPT_DISABLED* LEV_OPT_DEFERRED_ACCEPT

回调函数如下:

typedef void (*evconnlistener_cb)(struct evconnlistener *listener,evutil_socket_t sock, struct sockaddr *addr, int len, void *ptr)

`evconnlistener`为接收连接的`evconnlistener`对象,`sock`为套接字,`addr`和`len`为请求的地址和其长度,`ptr`是传给`evconnlistener_new`的。

开启和关闭连接监听

int evconnlistener_disable(struct evconnlistener *lev);int evconnlistener_enable(struct evconnlistener *lev);

改变回调函数

void evconnlistener_set_cb(struct evconnlistener *lev, evconnlistener_cb cb, void *arg);

检测当前evconnlistener

evutil_socket_t evconnlistener_get_fd(struct evconnlistener *lev); /* 获取sockfd */struct event_base *evconnlistener_get_base(struct evconnlistener *lev); /* 获取event_base */

检测错误

typedef void (*evconnlistener_errorcb)(struct evconnlistener *lis, void *ptr);void evconnlistener_set_error_cb(struct evconnlistener *lev, evconnlistener_errorcb errorcb);

该函数为错误设置回调函数,每当`listener`发生错误都会触发回调函数的执行。

bufferevent

Libevent的evbuffer功能通过实现一个字节队列,在队列末尾添加数据,在队列头移除数据。

结构

struct bufferevent {    struct event_base *ev_base;    const struct bufferevent_ops *be_ops;    struct event ev_read;    struct event ev_write;    struct evbuffer *input;    struct evbuffer *output;    ……    bufferevent_data_cb readcb;    bufferevent_data_cb writecb;    bufferevent_event_cb errorcb;    ……};

创建基于套接字的bufferevent

基于套接字的bufferevent是最简单的,它使用libevent的底层事件机制来检测底层网络套接字是否已经就绪,可以进行读写操作,并且使用底层网络调用(如readv、writev、WSASend、WSARecv)来发送和接收数据。

struct bufferevent * bufferevent_socket_new(struct event_base *base, evutil_socket_t fd, int options);struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); //例子 

设置读写回调函数

void bufferevent_setcb(struct bufferevent *bufev, bufferevent_data_cb readcb, bufferevent_data_cb writecb, bufferevent_event_cb eventcb, void *cbarg);bufferevent_setcb(bev, readcb, NULL, errorcb, NULL); //例子

启用事件

int bufferevent_enable(struct bufferevent *bufev, short event);bufferevent_enable(bev, EV_READ|EV_WRITE); //例子

线程安全

默认情况下,多线程同时访问evbuffer是不安全的。如果您需要执行此操作,您可以在evbuffer上调用 evbuffer_enable_locking()函数。如果此函数的lock参数为 NULL,则 Libevent 通过evthread_set_lock_creation_callback函数分配一把新锁。否则,它所使用的参数作为该锁。

int evbuffer_enable_locking(struct evbuffer *buf, void *lock);void evbuffer_lock(struct evbuffer *buf);void evbuffer_unlock(struct evbuffer *buf);

实例

/* Example code: an echo server. */#include <event2/listener.h>#include <event2/bufferevent.h>#include <event2/buffer.h>#include <arpa/inet.h>#include <string.h>#include <stdlib.h>#include <stdio.h>#include <errno.h>static voidecho_read_cb(struct bufferevent *bev, void *ctx){    /* 获取bufferevent中的读和写的指针 */    /* This callback is invoked when there is data to read on bev. */    struct evbuffer *input = bufferevent_get_input(bev);    struct evbuffer *output = bufferevent_get_output(bev);    /* 把读入的数据全部复制到写内存中 */    /* Copy all the data from the input buffer to the output buffer. */    evbuffer_add_buffer(output, input);}static void echo_event_cb(struct bufferevent *bev, short events, void *ctx){    if (events & BEV_EVENT_ERROR)        perror("Error from bufferevent");    if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {        bufferevent_free(bev);    }}static void accept_conn_cb(struct evconnlistener *listener,evutil_socket_t fd, struct sockaddr *address, int socklen,void *ctx){    /* 初始化一个bufferevent用于数据的写入和读取,首先需要从Listerner中获取event_base */    /* We got a new connection! Set up a bufferevent for it. */   struct event_base *base = evconnlistener_get_base(listener);   struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);    /* 设置buferevent的回调函数,这里设置了读和事件的回调函数 */   bufferevent_setcb(bev, echo_read_cb, NULL, echo_event_cb, NULL);    /* 启用该bufevent写和读 */     bufferevent_enable(bev, EV_READ|EV_WRITE);}static voidaccept_error_cb(struct evconnlistener *listener, void *ctx){    struct event_base *base = evconnlistener_get_base(listener);    int err = EVUTIL_SOCKET_ERROR();    fprintf(stderr, "Got an error %d (%s) on the listener. ""Shutting down.\n", err, evutil_socket_error_to_string(err));    event_base_loopexit(base, NULL);}intmain(int argc, char **argv){    struct event_base *base;    struct evconnlistener *listener;    struct sockaddr_in sin;    int port = 9876;    if (argc > 1) {        port = atoi(argv[1]);    }    if (port<=0 || port>65535) {        puts("Invalid port");        return 1;    }    base = event_base_new(); /* 初始化event_base */    if (!base) {        puts("Couldn‘t open event base");        return 1;    }    /* 初始化绑定地址 */    /* Clear the sockaddr before using it, in case there are extra    * platform-specific fields that can mess us up. */   memset(&sin, 0, sizeof(sin));    /* This is an INET address */    sin.sin_family = AF_INET;    /    * Listen on 0.0.0.0 */    sin.sin_addr.s_addr = htonl(0);    /* Listen on the given port. */    sin.sin_port = htons(port);    /* 初始化evconnlistener(绑定地址、设置回调函数以及连接属性) */    listener = evconnlistener_new_bind(base, accept_conn_cb, NULL, LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,(struct sockaddr*)&sin, sizeof(sin));    if (!listener) {        perror("Couldn‘t create listener");        return 1;    }    /* 设置Listen错误回调函数 */    evconnlistener_set_error_cb(listener, accept_error_cb);    / 开始accept进入循环 */    event_base_dispatch(base);    return 0;}             

 

libevent (二) 接收TCP连接