Libevent调用
生活随笔
收集整理的這篇文章主要介紹了
Libevent调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
http://blog.chinaunix.net/uid-15145533-id-2775910.html
http://blog.chinaunix.net/uid-15145533-id-2775909.html
總結
以上是生活随笔為你收集整理的Libevent调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux软连接和硬链接
- 下一篇: linux下使用NetBeans调试li