Chinaunix首页 | 论坛 | 博客
  • 博客访问: 841075
  • 博文数量: 150
  • 博客积分: 5123
  • 博客等级: 大校
  • 技术积分: 1478
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 10:03
文章分类

全部博文(150)

文章存档

2011年(2)

2010年(139)

2009年(9)

分类: C/C++

2010-10-02 08:47:04


程序名称为e.c,编译方法:gcc -g e.c -o e -levent

#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);
}


阅读(2248) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~