Monday, September 28, 2009

a simple http server with libevent

I'm starting my "stupid code tricks" by digging into libevent. This is how I wrote my first http server that should be able to quickly serve zillions of requests:

1. Download lib event, extract it, make configure, make install.

2. simple.c:


#include <stdio.h>
#include <stdlib.h>
#include "event.h"
#include "evhttp.h"

short http_port = 9999;
char *http_addr = "127.0.0.1";
struct evhttp *http_server = NULL;

void request_handler(struct evhttp_request *req, void *arg)
{
struct evbuffer *evb = evbuffer_new();
fprintf(stdout, "Request for %s from %s\n", req->uri, req->remote_host);
evbuffer_add_printf(evb, "garbage");
evhttp_send_reply(req, HTTP_OK, "Hello", evb);
evbuffer_free(evb);
return;
}

int main (int argc, const char * argv[]) {

event_init();
http_server = evhttp_start(http_addr, http_port);
if (http_server == NULL) {
fprintf(stderr, "Error starting http server on port %d\n", http_port);
exit(1);
}

evhttp_set_gencb(http_server, request_handler, NULL);

fprintf(stderr, "Server started on port %d\n", http_port);

event_dispatch();

return 0;
}




3. Write a makefile:


INCDIRS = -I/usr/local/include
CC = gcc
CFLAGS = $(INCDIRS) -Wall -g -O2
LIBS = /usr/local/lib/libevent.a

all: simple

simple: simple.o
$(CC) $(CFLAGS) simple.o -g -O2 -o $@ $(LIBS)

%.o : %.c
$(CC) $(CFLAGS) -c $<

clean:
rm -f *.o simple


4. run it: ./simple

5. point a web browser to http://127.0.0.1:9999

That's it. More to come soon.

No comments:

Post a Comment