C++实现httpserver和httpclient 方法

转:https://www.cnblogs.com/cnxkey/articles/8777975.html

 

这里采用mongoose这个库来实现基本的httpserver和httpclient功能,非常简单,包含一个h文件,一个cpp文件到工程中就行了,无需编译,无需链接库。

mongoose库的地址:https://github.com/cesanta/mongoose#mongoose---embedded-web-server--embedded-networking-library

代码参见:https://www.cnblogs.com/cnxkey/articles/8777975.html  这个是C++11的. vs2015以上的可以用.

 

其它参见: https://cesanta.com/docs/overview/intro.html   官网教程.

                 https://github.com/cesanta/mongoose              源码

HTTP client example
To create an HTTP client, follow this pattern:

Create an outbound connection by calling mg_connect_http()
Create an event handler function that handles MG_EV_HTTP_REPLY event
Here's an example of the simplest HTTP client. Error checking is omitted for the sake of clarity:

#include "mongoose.h"

static const char *url = "http://www.google.com";
static int exit_flag = 0;

static void ev_handler(struct mg_connection *c, int ev, void *p) {
  if (ev == MG_EV_HTTP_REPLY) {
    struct http_message *hm = (struct http_message *)p;
    c->flags |= MG_F_CLOSE_IMMEDIATELY;
    fwrite(hm->message.p, 1, (int)hm->message.len, stdout);
    putchar('\n');
    exit_flag = 1;
  } else if (ev == MG_EV_CLOSE) {
    exit_flag = 1;
  };
}

int main(void) {
  struct mg_mgr mgr;

  mg_mgr_init(&mgr, NULL);
  mg_connect_http(&mgr, ev_handler, url, NULL, NULL);


  while (exit_flag == 0) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);

  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值