安装
下载完libevent后:
1. sudo apt-get install automake libtool
2. cd libevent
3. git checkout 2.0.23-stable-rc
4. ./autogen.sh
5. ./configure
6. make
7. sudo make install
1)进入到libevent目录,执行:
git checkout 2.0.23-stable-rc // 切换分支
./autogen.sh
2)
./configure
make
sudo make install
安装位置:
- 头文件:/usr/local/include
- 库文件:/usr/local/lib
HelloWorld
1)新建一个event_base (类似于于创建一个epoll或者select对象) linux下默认是epoll
struct event_base *evbase = event_base_new();
创建事件
struct event *server_ev = event_new(evbase, server, EV_READ | EV_ET, server_callback, NULL);
//server 是描述符
//server_callback是回调函数
将事件添加到event_base 里面
event_add(server_ev, NULL);
通过event_base获取socket事件 (循环的)
event_base_dispatch(evbase);
event_base释放
event_base_free(event);
代码一:
t01_cilent.c
#include "../h.h"
int main()
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9988);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int ret = connect(sock, (struct sockaddr*)&addr, sizeof(addr));
if (ret < 0)
{
perror("connect err");
return -1;
}
char buf[] = "hello world\n";
send(sock, buf, sizeof(buf), 0);
close(sock);
return 0;
}
t01_libevent_hello.c
#include "../h.h"
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <inttypes.h>
void eventcb(struct bufferevent *bev, short what, void *ctx)
{
if ((what & BEV_EVENT_EOF) > 0)
{
printf("delete event\n");
bufferevent_free(bev);
}
}
// socket has data in bufferevent
void readcb(struct bufferevent *bev, void *ctx)
{
// read data from bufferevent
char buf[1024] = { 0 };
// 从bufferevent中抽取数据
int ret = bufferevent_read(bev, buf, sizeof(buf));
if (ret < 0)
{
perror("bufferevent_read err");
}
printf("%s\n", buf);
}
/*
* listener: 监听器
* newfd: accept返回的socket
* addr: 是对端的网络地址
* socklen: 对端的网络地址结构体的长度
* ptr: 额外参数
*/
void listen_cb(struct evconnlistener *listener, evutil_socket_t newfd, struct sockaddr *addr, int socklen, void *ptr)
{
// get evbase
struct event_base *evbase = evconnlistener_get_base(listener);
// add newfd to evbase
struct bufferevent *bev = bufferevent_socket_new(evbase, newfd, BEV_OPT_CLOSE_ON_FREE);
// setup read and event callback function
bufferevent_setcb(bev, readcb, NULL, eventcb, NULL);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
int main()
{
/* 类似创建一个epoll或者select对象,默认Linux下是epoll
* event_base是一个时间的集合
* 在libevent中,事件指一件即将要发生的事情,evbase就是用来监控这些事件的
* 发生(激活)的条件的
*/
struct event_base *evbase = event_base_new();
struct sockaddr_in addr;
addr.sin_port = htons(9988);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
// 创建一个监听器事件,该监听器事件是初始化的状态
struct evconnlistener* listener =
evconnlistener_new_bind(
evbase,
listen_cb,
NULL,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
250,
(struct sockaddr*)&addr,
sizeof(addr));
// 进入未决状态
evconnlistener_enable(listener);
// evbase监听它的所有未决状态的事件,进入死循环
event_base_dispatch(evbase);
// 释放event_base
event_base_free(evbase);
return 0;
}
编译要加链接库:
gcc t01_libevent_hello.c -o server -levent_core;