Libevent應用 (五) 連線監聽器,接收tcp連線

嚇人的猿發表於2018-03-03

5 連線監聽器,接收tcp連線

5.1  建立和釋放evconnlistener

#include <event2/listener.h>
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_new_bind()函式分配和返回一個新的連線監聽器物件。連線監聽器使用event_base來得知什麼時候在給定的監聽套接字上有新的TCP連線。新連線到達時,監聽器呼叫你給出的回撥函式。

​ 兩個函式中,base引數都是監聽器用於監聽連線的event_base。cb是收到新連線時要呼叫的回撥函式;如果cb為NULL,則監聽器是禁用的,直到設定了回撥函式為止。ptr指標將傳遞給回撥函式。flags引數控制回撥函式的行為,下面會更詳細論述。backlog是任何時刻網路棧允許處於還未接受狀態的最大未決連線數。如果backlog是負的,libevent會試圖挑選一個較好的值;如果為0,libevent認為已經對提供的套接字呼叫了listen()。

​ 兩個函式的不同在於如何建立監聽套接字。evconnlistener_new()函式假定已經將套接字繫結到要監聽的埠,然後通過fd傳入這個套接字。如果要libevent分配和繫結套接字,可以呼叫evconnlistener_new_bind(),傳輸要繫結到的地址和地址長度。

可以給evconnlistener_new()函式的flags引數傳入一些標誌。可以用或(OR)運算任意連線下述標誌:

LEV_OPT_LEAVE_SOCKETS_BLOCKING
/*預設情況下,連線監聽器接收新套接字後,會將其設定為非阻塞的,
以便將其用於libevent。如果不想要這種行為,可以設定這個標誌。*/
  
LEV_OPT_CLOSE_ON_FREE
/*如果設定了這個選項,釋放連線監聽器會關閉底層套接字。*/
  
LEV_OPT_CLOSE_ON_EXEC
/*如果設定了這個選項,連線監聽器會為底層套接字設定close-on-exec標誌。*/
  
LEV_OPT_REUSEABLE
/*設定這個標誌會讓libevent標記套接字是可重用的,這樣一旦關閉,
可以立即開啟其他套接字,在相同埠進行監聽。*/
  
LEV_OPT_THREADSAFE
/*為監聽器分配鎖,這樣就可以在多個執行緒中安全地使用了。*/


連線監聽器回撥函式:

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

​ 接收到新連線會呼叫提供的回撥函式。listener引數是接收連線的連線監聽器。sock引數是新接收的套接字。addr和len引數是接收連線的地址和地址長度。ptr是呼叫evconnlistener_new()時使用者提供的指標。

​ 要釋放連線監聽器,呼叫evconnlistener_free()。

5.2 啟用和禁用evconnlistener

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

這兩個函式暫時禁止或者重新允許監聽新連線。

5.3 調整evconnlistener的回撥函式

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

函式調整evconnlistener的回撥函式和其引數。

5.4 獲取event_base

struct event_base *evconnlistener_get_base(struct evconnlistener *lev);

5.5示例程式碼

伺服器端:tcp_server.c

/*************************************************************************
# File Name: tcp_server.c
# Author: wenong
# mail: huangwenlong@520it.com
# Created Time: 2016年09月03日 星期六 21時51分08秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#define SERVERPORT 8888
#define MAXBYTES 1024

static struct event_base * base;

void write_buf_cb(struct bufferevent* bev, void* cbarg)
{
    printf("%s\n", __FUNCTION__);
}

void read_buf_cb(struct bufferevent* bev, void* cbarg)
{
    int ret, i;
    char buf[MAXBYTES];
    ret = bufferevent_read(bev, buf, sizeof(buf));
    printf("read_buf_cd length %d\n", ret);
    for(i = 0; i < ret; i++)
    {
        buf[i] = toupper(buf[i]);
    }
    bufferevent_write(bev, buf, ret);
    
}


void event_cb(struct bufferevent* bev, short event, void* cbarg)
{
    if(BEV_EVENT_READING & event)
        puts("BEV_EVENT_READING");
    
    if(BEV_EVENT_WRITING & event)
        puts("BEV_EVENT_WRITING");

    if(BEV_EVENT_ERROR & event)
        puts("BEV_EVENT_ERROR");

    if(BEV_EVENT_EOF & event)
    {
        puts("BEV_EVENT_EOF");
        bufferevent_free(bev);
    }
    if(BEV_EVENT_TIMEOUT & event)
    {
        puts("BEV_EVENT_TIMEOUT");
        bufferevent_free(bev);
    }
}


void  accept_cb(struct evconnlistener *listener,
            evutil_socket_t clientfd, struct sockaddr *addr
            , int len, void *arg)
{
    
    struct bufferevent* bev;
    struct event_base* base = (struct event_base*)arg;
    puts("Accept client connect");

    evutil_make_socket_nonblocking(clientfd);
    bev = bufferevent_socket_new(base, clientfd, BEV_OPT_CLOSE_ON_FREE 
            | BEV_OPT_DEFER_CALLBACKS);
    bufferevent_setcb(bev, (bufferevent_data_cb)read_buf_cb
            , (bufferevent_data_cb)write_buf_cb, (bufferevent_event_cb)event_cb, NULL);
  
    struct timeval timeout_read = {10, 0};
    bufferevent_set_timeouts(bev, &timeout_read, NULL);  
    bufferevent_setwatermark(bev, EV_READ, 10, 0);
    bufferevent_setwatermark(bev, EV_WRITE, 10, 0);

    bufferevent_enable(bev, EV_READ | EV_WRITE);
}

void main_loop(struct sockaddr_in * addr)
{
    
    struct evconnlistener *evcon;
    base = event_base_new();
    evcon = evconnlistener_new_bind(base, (evconnlistener_cb)accept_cb
            , (void*)base, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE
            , 128, (struct sockaddr*)addr, sizeof(struct sockaddr_in));

    puts("server begin listenning...");


    event_base_dispatch(base);
    evconnlistener_free(evcon);
    event_base_free(base);

}


int main(int argc, char** argv)
{
    int serverfd;
    socklen_t serveraddrlen;
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;    
    serveraddr.sin_port = htons(SERVERPORT);
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverfd = socket(AF_INET, SOCK_STREAM, 0);
    serveraddrlen = sizeof(serveraddr);
    main_loop( &serveraddr);

    return 0;
}

客戶端程式碼:tcp_client.c

/*************************************************************************
# File Name: tcp_client.c
# Author: wenong
# mail: huangwenlong@520it.com
# Created Time: 2016年09月03日 星期六 22時10分11秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <errno.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#define SERVERIP "127.0.0.1"
#define SERVERPORT 8888
#define MAXBYTES 1024
static struct sockaddr_in serveraddr;
static struct event_base* base;
static struct bufferevent* bev;

void* cmd_msg_cb(evutil_socket_t stdinfd, short what, void* arg)
{
    int ret;
    char buf[MAXBYTES];
    ret = read(stdinfd, buf, sizeof(buf));
    bufferevent_write(bev, buf, ret);
}

void read_buf_cb(struct bufferevent* bev, void* cbarg)
{
    int ret;
    char buf[MAXBYTES];
    ret = bufferevent_read(bev, buf, sizeof(buf));
    write(STDOUT_FILENO, buf, ret);
}

void event_cb(struct bufferevent* bev, short event, void* cbarg)
{
    if(BEV_EVENT_READING & event)
        puts("BEV_EVENT_READING");
    
    if(BEV_EVENT_WRITING & event)
        puts("BEV_EVENT_WRITING");

    if(BEV_EVENT_ERROR & event)
        printf("BEV_EVENT_ERROR %s\n", strerror(EVUTIL_SOCKET_ERROR())); //獲取錯誤資訊

    if(BEV_EVENT_CONNECTED & event)
        puts("BEV_EVENT_CONNECTED");

    if(BEV_EVENT_EOF & event)
    {
        puts("BEV_EVENT_EOF");
        event_base_loopexit(base, NULL);
    }
    if(BEV_EVENT_TIMEOUT & event)
    {
        puts("BEV_EVENT_TIMEOUT");
        event_base_loopexit(base, NULL);
    }


}
void main_loop()
{
    struct event*ev_stdin;  

    base = event_base_new();
    bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE 
            | BEV_OPT_DEFER_CALLBACKS);

    bufferevent_setcb(bev, (bufferevent_data_cb)read_buf_cb
            , NULL, (bufferevent_event_cb)event_cb, NULL);

    bufferevent_socket_connect(bev, (struct sockaddr*)&serveraddr, sizeof(struct sockaddr_in));

    struct timeval timeout_read;
    timeout_read.tv_sec = 10;
    timeout_read.tv_usec = 0;
    bufferevent_set_timeouts(bev, &timeout_read, NULL);  
  
    bufferevent_enable(bev, EV_READ);


    ev_stdin = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST
            , (event_callback_fn)cmd_msg_cb, NULL);
    event_add(ev_stdin, NULL);

    event_base_dispatch(base);
    bufferevent_free(bev);
    event_free(ev_stdin);
    event_base_free(base);
    puts("exit now...");
}

int main(int argc, char** argv)
{
    serveraddr.sin_family = AF_INET;
    inet_pton(AF_INET, SERVERIP, &serveraddr.sin_addr.s_addr);
    serveraddr.sin_port = htons(SERVERPORT);
    main_loop();
    return 0;
}

相關文章