没有合适的资源?快使用搜索试试~ 我知道了~
接写一个很简单的 Time Server 来当作例子:当你连上去以后 Server 端直接提供时间,然后结束连线。event_init() 表示初始化 libevent 所使用到的变数。event_set(&ev, s, EV_READ | EV_PERSIST, connection_accept, &ev) 把 s 这个 File Description 放入 ev (第一个参数与第二个参数),并且告知当事件 (第三个参数的 EV_READ) 发生时要呼叫 connection_accept() (第四个参数),呼叫时要把 ev 当作参数丢进去 (第五个参数)。其中的 EV_PERSIST
资源详情
资源评论
资源推荐
libevent库的使用方法实例库的使用方法实例
接写一个很简单的 Time Server 来当作例子:当你连上去以后 Server 端直接提供时间,然后结束连线。event_init() 表示初始
化 libevent 所使用到的变数。event_set(&ev, s, EV_READ | EV_PERSIST, connection_accept, &ev) 把 s 这个 File
Description 放入 ev (第一个参数与第二个参数),并且告知当事件 (第三个参数的 EV_READ) 发生时要呼叫
connection_accept() (第四个参数),呼叫时要把 ev 当作参数丢进去 (第五个参数)。其中的 EV_PERSIST 表示当呼叫进去的
时候不要把这个 event 拿掉 (继续保留在 Event Queue 里面),这点可以跟 connection_accept() 内在注册 connection_time()
的代码做比较。而 event_add(&ev, NULL) 就是把 ev 注册到 event queue 里面,第二个参数指定的是 Timeout 时间,设定成
NULL 表示忽略这项设定。
注:这段代码来自于网络,虽然很粗糙,但是对libevent的使用方法已经说明的很清楚了.
附源码:
代码如下:
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <event.h>
#include <stdio.h>
#include <time.h>
void connection_time(int fd, short event, struct event *arg)
{
char buf[32];
struct tm t;
time_t now;
time(&now);
localtime_r(&now, &t);
asctime_r(&t, buf);
write(fd, buf, strlen(buf));
shutdown(fd, SHUT_RDWR);
free(arg);
}
void connection_accept(int fd, short event, void *arg)
{
/* for debugging */
fprintf(stderr, “%s(): fd = %d, event = %d.”, __func__, fd, event);
/* Accept a new connection. */
struct sockaddr_in s_in;
socklen_t len = sizeof(s_in);
int ns = accept(fd, (struct sockaddr *) &s_in, &len);
if (ns < 0) {
perror(“accept”);
return;
}
/* Install time server. */
struct event *ev = malloc(sizeof(struct event));
event_set(ev, ns, EV_WRITE, (void *) connection_time, ev);
event_add(ev, NULL);
}
weixin_38631454
- 粉丝: 5
- 资源: 932
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0