libev学习(一)初识libev

libev内部封装了socket IO 模型,用户只需要向感兴趣的事件注册回调函数,简化了socket服务端编程。

先贴上一段socket编程中的hello world,echo服务器代码,对libev的用法有大致印象

#include 
#include 
#include 
#include 
#include 
#include 
#include "ev.h"

#define PORT 65530
#define BUFFER_SIZE 512

void accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents);
void read_cb(struct ev_loop *loop, struct ev_io *watcher, int revents);

int main()
{
    struct ev_loop *loop = ev_default_loop(0);
    int sd;
    struct sockaddr_in addr;
    int addr_len = sizeof(addr);
    struct ev_io socket_accept;

    if ( (sd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
        printf("Failed socket().\n");
        return -1;
    }

    bzero (&addr, addr_len);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(sd, (struct sockaddr*)&addr, addr_len) != 0) {
        printf("Failed bind().\n");
        return -2;
    }

    if (listen(sd, 2) < 0) {
        printf("Failed listen().\n");
        return -3;
    }

    ev_io_init(&socket_accept, accept_cb, sd, EV_READ);
    ev_io_start(loop, &socket_accept);

    while (1) {
        ev_loop(loop, 0);
    }

    return 0;
}

void accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents) 
{
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    int client_sd;

    struct ev_io *w_client = (struct ev_io *)malloc(sizeof(struct ev_io));

    if (EV_ERROR & revents) {
        printf("error event in accept");
        return;
    }

    client_sd = accept(watcher->fd, (struct sockaddr*)&client_addr, &client_len);
    if (client_sd < 0) {
        printf("accept error.\n");
        return;
    }

    printf("connected from %s:%d\n", inet_ntoa(client_addr.sin_addr),
            ntohs(client_addr.sin_port)  );

    ev_io_init(w_client, read_cb, client_sd, EV_READ);
    ev_io_start(loop, w_client);
}

void read_cb(struct ev_loop *loop, struct ev_io *watcher, int revent)
{
    char buffer[BUFFER_SIZE];
    ssize_t read;

    if (EV_ERROR & revent) {
        printf("error event in read.\n");
        return;
    }

    read = recv(watcher->fd, buffer, BUFFER_SIZE, 0);
    if (read < 0) {
        printf("read error.\n");
        return;
    }

    if (0 == read) {
        printf("client disconnected.\n");
        ev_io_stop(loop, watcher);
        free(watcher);
        return;
    }

    printf("read message:%s(%ld)\n", buffer, read);
    send(watcher->fd, buffer, read, 0);
    bzero(buffer, read);
}

你可能感兴趣的:(C/C++)