libevent和libcurl的一些学习

libevent和libcurl的一些学习

libcurl是一个用于传递数据的库;libevent则是提供服务器相应操作的库。

网上关于libcurl的介绍很多,主要介绍了如何用它下载网页等功能,另外网上也有许多相关php代码的实例。libevent的相关资源比较少。

一下是我实现的两个简单的小例子,一个利用libcurl发送数据,一个利用libevent去接收。

libcurl.c 发送数据

?
1 #include<curl/curl.h>
2 #include<stdio.h>
3 int main( void ){
4 char *url= "http://127.0.0.1:8080/test" ;
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 ){
12 char *api_uri= "http://127.0.0.1" ;
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 }

关于这两个库的比较好的学习地址:

http://curl.haxx.se/

http://monkey.org/~provos/libevent/

http://newblog.csdn.net/jgood/article/details/4787670

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值