libevent库的使用方法实例

这篇文章主要介绍了libevent库的使用方法实例,有需要的朋友可以参考一下

接写一个很简单的 Time Server 来当作例子:当你连上去以后 Server 端直接提供时间,然后结束连线。event_init() 表示初始化 libevent 所使用到的变数。event_set(&ev, s, EV_READ | EV_PERSIST, connection_accept, &ev) 把 s 这个 File Description 放入 ev (第一个参数与第二个参数),并且告知当事件 (第三个参数的 EV_READ) 发生时要呼叫 connection_accept() (第四个参数),呼叫时要把 ev 当作参数丢进去 (第五个参数)。其中的 EV_PERSIST 表示当呼叫进去的时候不要把这个 event 拿掉 (继续保留在 Event Queue 里面),这点可以跟 connection_accept() 内在注册 connection_time() 的代码做比较。而 event_add(&ev, NULL) 就是把 ev 注册到 event queue 里面,第二个参数指定的是 Timeout 时间,设定成 NULL 表示忽略这项设定。
注:这段代码来自于网络,虽然很粗糙,但是对libevent的使用方法已经说明的很清楚了.
附源码:

复制代码 代码如下:

#include   
#include   
#include   
#include   
#include   
#include   

void connection_time(int fd, short event, struct event *arg)  
{  
    char buf[32];  
    struct tm t;  
    time_t now;  

    time(&now);  
    localtime_r(&now, &t);  
    asctime_r(&t, buf);  

    write(fd, buf, strlen(buf));  
    shutdown(fd, SHUT_RDWR);  

    free(arg);  
}  

void connection_accept(int fd, short event, void *arg)  
{  
    /* for debugging */
    fprintf(stderr, "%s(): fd = %d, event = %d.\n", __func__, fd, event);  

    /* Accept a new connection. */
    struct sockaddr_in s_in;  
    socklen_t len = sizeof(s_in);  
    int ns = accept(fd, (struct sockaddr *) &s_in, &len);  
    if (ns <0) {  
        perror("accept");  
        return;  
    }  

    /* Install time server. */
    struct event *ev = malloc(sizeof(struct event));  
    event_set(ev, ns, EV_WRITE, (void *) connection_time, ev);  
    event_add(ev, NULL);  
}  

int main(void)  
{  
    /* Request socket. */
    int s = socket(PF_INET, SOCK_STREAM, 0);  
    if (s <0) {  
        perror("socket");  
        exit(1);  
    }  

    /* bind() */
    struct sockaddr_in s_in;  
    bzero(&s_in, sizeof(s_in));  
    s_in.sin_family = AF_INET;  
    s_in.sin_port = htons(7000);  
    s_in.sin_addr.s_addr = INADDR_ANY;  
    if (bind(s, (struct sockaddr *) &s_in, sizeof(s_in)) <0) {  
        perror("bind");  
        exit(1);  
    }  

    /* listen() */
    if (listen(s, 5) <0) {  
        perror("listen");  
        exit(1);  
    }  

    /* Initial libevent. */
    event_init();  

    /* Create event. */
    struct event ev;  
    event_set(&ev, s, EV_READ | EV_PERSIST, connection_accept, &ev);  

    /* Add event. */
    event_add(&ev, NULL);  

    event_dispatch();  

    return 0;  
}

以上就是libevent库的使用方法实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言