http://kukuruku.co/hub/cpp/lightweight-http-server-in-less-than-40-lines-on-libevent-and-c-11

 

and the following :

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <event.h>

struct _targs {
    struct bufferevent ** pair;
    struct event        * ev;
};

static void
_write(struct bufferevent * bev, void * arg) {
    printf("-- _write: %zu\n", evbuffer_get_length(bev->output));
    evbuffer_drain(bev->output, evbuffer_get_length(bev->output));
}

static void
_read(struct bufferevent * bev, void * arg) {
    printf("-- _read: %zu\n", evbuffer_get_length(bev->input));
    printf("-- _read: %s\n", (char *)evbuffer_pullup(bev->input, -1));

    evbuffer_drain(bev->input, evbuffer_get_length(bev->input));
}

static void
_do_write(int sock, short which, void * arg) {
    struct _targs * targs = (struct _targs *)arg;
    struct timeval  tv;

    bufferevent_write(targs->pair[0], "HERP\0", 5);

    tv.tv_sec  = 5;
    tv.tv_usec = 0;

    evtimer_add(targs->ev, &tv);
}

int
main(int argc, char ** argv) {
    struct event_base  * evbase;
    struct bufferevent * pair[2];
    struct bufferevent * p1;
    struct bufferevent * p2;
    struct event       * timer;
    struct timeval       tv;
    struct _targs      * targs;

    evbase = event_base_new();

    bufferevent_pair_new(evbase, 0, pair);

    p1          = pair[0];
    p2          = pair[1];

    tv.tv_sec   = 5;
    tv.tv_usec  = 0;
    targs       = malloc(sizeof(struct _targs));
    timer       = evtimer_new(evbase, _do_write, (void *)targs);

    targs->pair = pair;
    targs->ev   = timer;

    bufferevent_setcb(p1, NULL, _write, NULL, NULL);
    bufferevent_setcb(p2, _read, NULL, NULL, NULL);

    bufferevent_disable(p1, EV_READ);
    bufferevent_enable(p2, EV_READ);
    bufferevent_write(p1, "DERP\0", 5);

    evtimer_add(timer, &tv);
    event_base_loop(evbase, 0);

    return 0;
}

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()