1.最基本的打印libevent版本
#include <event.h>
#include <stdio.h>
int main()
{
const char *version = event_get_version();
printf("%s\n",version);
return 0;
}
# gcc getVersion.c -o getVersion -levent
参考:https://github.com/mike-zhang/testCodes/tree/master/libeventTest
2.echoServer
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <event.h>
void sock_read(int fd, short event, void *arg)
{
char buf[255];
int len;
struct event *ev = arg;
len = recv(fd, buf, sizeof(buf)-1, 0);
if (len == -1)
{
perror("recv error\n");
if (errno != EAGAIN && errno != EINTR)
{
close(fd);
free(ev);
}
return;
}
else if (len == 0)
{
close(fd);
fprintf(stderr, "Connection closed\n");
free(ev);
return;
}
buf[len] = '\0';
fprintf(stdout, "Read: %s\n", buf);
/* Reschedule this event */
/* 重新安排此事件 */
event_add(ev, NULL);
}
void sock_accept(int fd, short event, void *arg)
{
struct event *ev = arg;
struct sockaddr addr;
socklen_t len = sizeof(addr);
//由于此结构要长期使用,所以rev必须动态分配,否则离开此函数后会自动释放,导致段错误
struct event* rev = (struct event*)malloc(sizeof(*rev));
int s = accept(fd, &addr, &len);
if (s == -1)
{
perror("accept error\n");
return;
}
fprintf(stdout, "accept socket: %d\n", s);
/* Initialize one event */
/* 初始化一个事件 */
event_set(rev, s, EV_READ, sock_read, rev);
/* Add it to the active events, without a timeout */
/* 将它添加到活动事件,不超时 */
event_add(rev, NULL);
/* Reschedule this event */
/* 重新安排此事件 */
event_add(ev, NULL);
}
int main (int argc, char **argv)
{
struct event ev;
int fd;
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
perror("socket error\n");
exit(-1);
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(10000);
addr.sin_addr.s_addr = 0;
if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
{
perror("bind error\n");
exit(-1);
}
if (listen(fd, 5) == -1)
{
perror("listen error\n");
exit(-1);
}
/* Initalize the event library */
/* 初始化一个事件库 */
event_init();
/* Initalize one event */
/* 初始化一个事件. */
event_set(&ev, fd, EV_READ, sock_accept, &ev);
/* Add it to the active events, without a timeout */
/* 将它添加到活动事件,不超时 */
event_add(&ev, NULL);
event_dispatch();
return (0);
}
编译:
# gcc myevent.c -o myevent -Wl,-rpath,/usr/local/libevent/lib/ -L/usr/local/libevent/lib/ -levent -I/usr/local/libevent/include/
启动:
# ./echoServer
#telnet 127.0.0.1 10000
退出
方法:
1、ctrl+]
2、quit
参考:
http://blog.linuxphp.org/archives/1482/ http://blog.linuxphp.org/archives/1487/ http://blog.linuxphp.org/archives/1488/
http://blog.chinaunix.net/uid-25885064-id-3399488.html
http://www.cnblogs.com/ggjucheng/archive/2012/02/02/2335495.html
http://www.cnblogs.com/cnspace/archive/2011/07/19/2110891.html