libevent和libcurl的一些学习
libcurl是一个用于传递数据的库;libevent则是提供服务器相应操作的库。
网上关于libcurl的介绍很多,主要介绍了如何用它下载网页等功能,另外网上也有许多相关php代码的实例。libevent的相关资源比较少。
一下是我实现的两个简单的小例子,一个利用libcurl发送数据,一个利用libevent去接收。
libcurl.c 发送数据
1 #include<curl/curl.h>
2 #include<stdio.h>
3
int
main(
void
){
5
char
mypost[]=
"asdfasdfasdfsdf"
;
6
// mypost[4]='\0';
7
// CURLcode return_code;
8
// return_code=curl_global_init(CURL_GLOBAL_WIN32);
9 CURL *curl=curl_easy_init();
10
if
(curl==NULL){
11
perror
(
"get a easy heandle failed.\n"
);
12 curl_easy_cleanup(curl);
13 curl_global_cleanup();
14
return
-1;
15 }
16 curl_easy_setopt(curl,CURLOPT_HEADER,1);
17 curl_easy_setopt(curl,CURLOPT_URL,url);
18 curl_easy_setopt(curl,CURLOPT_POST,1);
19 curl_easy_setopt(curl,CURLOPT_POSTFIELDS,(
void
*)mypost);
20 curl_easy_perform(curl);
21 curl_easy_cleanup(curl);
22
return
0;
23 }
|
libevent.c 接收数据
1 #include<stdio.h>
2 #include<evhttp.h>
3
void
test_handle(
struct
evhttp_request *r,
void
*u){
4 u_char *buf;
5 buf=EVBUFFER_DATA(r->input_buffer);
6 evhttp_send_reply(r,200,
"read ok!"
,NULL);
7
printf
(
"the host is: %s \n"
,r->remote_host);
8
printf
(
"the data is:\n%s\n"
,buf);
9
return
;
10 }
11
int
main(
void
){
13
struct
event_base *base;
14
struct
evhttp *http;
15 base =event_base_new();
16 http=evhttp_new(base);
17
if
(!http){
18
perror
(
"evhttp_new() failed"
);
19
return
-1;
20 }
21
if
(evhttp_bind_socket(http,
"0.0.0.0"
,8080)){
22
perror
(
"bind_sock() failed"
);
23
return
-1;
24 }
25
//evhttp_set_cb(http,"/",test_handle,NULL);
26 evhttp_set_gencb(http,test_handle,NULL);
27 event_base_dispatch(base);
28 evhttp_free(http);
29 event_base_free(base);
30
return
0;
31 }
|
关于这两个库的比较好的学习地址: