现在的位置: 首页 > 编程语言 > 正文

使用libevent写的一个简单服务器的代码

2019年08月09日 编程语言 ⁄ 共 1910字 ⁄ 字号 评论关闭

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <event.h>

void sock_read(int fd, short event, void *arg)
{
    char buf[255];
    int len;
    struct event *ev = arg;

    len = recv(fd, buf, sizeof(buf)-1, 0);

    if (len == -1)
    {
        perror("recv error/n");

        if (errno != EAGAIN && errno != EINTR)
        {
            close(fd);
            free(ev);
        }

        return;
    }
    else if (len == 0)
    {
        close(fd);
        fprintf(stderr, "Connection closed/n");
        free(ev);
        return;
    }

    buf[len] = '/0';

    fprintf(stdout, "Read: %s/n", buf);

    /* Reschedule this event */
    event_add(ev, NULL);
}

void sock_accept(int fd, short event, void *arg)
{
    struct event *ev = arg;
    struct sockaddr addr;
    socklen_t len = sizeof(addr);

    //由于此结构要长期使用,所以rev必须动态分配,否则离开此函数后会自动释放,导致segment fault
    struct event* rev = (struct event*)malloc(sizeof(*rev));
    
    int s = accept(fd, &addr, &len);
    if (s == -1)
    {
        perror("accept error/n");
        return;
    }

    fprintf(stdout, "accept socket: %d/n", s);

    /* Initalize one event */
    event_set(rev, s, EV_READ, sock_read, rev);

    /* Add it to the active events, without a timeout */
    event_add(rev, NULL);

    /* Reschedule this event */
    event_add(ev, NULL);
}

int
main (int argc, char **argv)
{
    struct event ev;
    int fd;
    struct sockaddr_in addr;    
 
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        perror("socket error/n");
        exit(-1);
    }

    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(10000);
    addr.sin_addr.s_addr = 0;
    if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
    {
        perror("bind error/n");
        exit(-1);
    }

    if (listen(fd, 5) == -1)
    {
        perror("listen error/n");    
        exit(-1);
    }

    /* Initalize the event library */
    event_init();

    /* Initalize one event */
    event_set(&ev, fd, EV_READ, sock_accept, &ev);

    /* Add it to the active events, without a timeout */
    event_add(&ev, NULL);
    
    event_dispatch();

    return (0);
}

抱歉!评论已关闭.