Skip to content

Instantly share code, notes, and snippets.

@mythosil
Created August 6, 2011 09:51
Show Gist options
  • Save mythosil/1129233 to your computer and use it in GitHub Desktop.
Save mythosil/1129233 to your computer and use it in GitHub Desktop.
libevent sample (echo server)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <event.h>
#define PORT 1986
#define BACKLOG -1
#define BUFSIZE 256
void accept_handler(int listener, short event, void *arg);
void read_handler(int client, short event, void *arg);
int main(int argc, const char* argv[])
{
struct event ev;
struct sockaddr_in sin;
int listener;
listener = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(PORT);
bind(listener, (struct sockaddr*)&sin, sizeof(struct sockaddr));
listen(listener, BACKLOG);
event_init();
event_set(&ev, listener, EV_READ | EV_PERSIST, accept_handler, &ev);
event_add(&ev, NULL);
event_dispatch();
return 0;
}
void accept_handler(int listener, short event, void *arg)
{
struct event *ev;
struct sockaddr_in addr;
int client;
socklen_t addrlen = sizeof(addr);
if (event & EV_READ) {
client = accept(listener, (struct sockaddr*)&addr, &addrlen);
ev = (struct event*)malloc(sizeof(struct event));
event_set(ev, client, EV_READ | EV_PERSIST, read_handler, ev);
event_add(ev, NULL);
printf("connection accepted\n");
}
}
void read_handler(int client, short event, void *arg)
{
char buf[BUFSIZE];
struct event *ev = (struct event*)arg;
ssize_t recvlen;
if (event & EV_READ) {
if ((recvlen = recv(client, buf, sizeof(buf)-1, 0)) <= 0) {
event_del(ev);
free(ev);
close(client);
printf("connection closed\n");
} else {
buf[recvlen] = '\0';
send(client, buf, recvlen, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment