1.介绍

   简单且高效的事件驱动库实现,非常适合在嵌入式环境下使用,需要极少的资源占用

  • 支持定时器事件
  • 支持文件描述符事件
  • 可以在多线程中使用,每个线程都有一个事件循环
  • 目前支持在linux,macos下使用,linux使用epoll作为io复用器,macos使用kqueue

2.源码地址:https://github.com/huangyajie/libeloop

3.使用示例

 一个简单的echo 服务器

//simple echo server

#include "eloop.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static void read_cb (struct eloop_base* base,struct eloop_fd *efd, unsigned int events)
{
    fprintf(stderr,"have data\n");
    char buf[1024] = {0};
    int n = read(efd->fd,buf,sizeof(buf));
    if(n <= 0)
    {
        fprintf(stderr,"close connection\n");
        eloop_fd_delete(base,efd);
        close(efd->fd);
        free(efd);
        efd = NULL;
        return;
    }
    write(efd->fd,buf,n);
}

static void accept_cb (struct eloop_base* base,struct eloop_fd *efd, unsigned int events)
{
    fprintf(stderr,"new connection\n");

    struct sockaddr_in sin;
	unsigned int sl = sizeof(struct sockaddr_in);
	int cfd = accept(efd->fd, (struct sockaddr *) &sin, &sl);
	if (cfd < 0) 
    {
		fprintf(stderr, "Accept failed\n");
		return;
	}

    struct eloop_fd *pfd = (struct eloop_fd *)calloc(1,sizeof(*pfd));
    pfd->fd = cfd;
    pfd->cb = read_cb;
    eloop_fd_add(base,pfd,ELOOP_READ);

}

static int tcp_server_init(int port)
{
    int sock;

    struct sockaddr_in servaddr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
            return -1;

    
    const int one = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(port);

    if(bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0)
    {
        fprintf(stderr,"绑定端口失败\n");
        close(sock);
        return -3;
    }

    if(listen(sock, SOMAXCONN) != 0)
    {
        fprintf(stderr,"listen() 失败\n");
        close(sock);
        return -4;
    }
	
    return sock;
}

int main(int argc, char const *argv[])
{
    /* code */
    struct eloop_base* base = eloop_init();

    int sfd = tcp_server_init(5678);
    if(sfd < 0)
    {
        eloop_done(base);
        return -1;
    }
        
    
    struct eloop_fd efd;
    memset(&efd,0,sizeof(efd));

    efd.fd = sfd;
    efd.cb = accept_cb;

    eloop_fd_add(base,&efd,ELOOP_READ);

    eloop_run(base);
    eloop_done(base);

    return 0;
}

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐