基于cpp-httplib库与多线程实现的http请求

1、cpp-httplib官网,使用只需要包含一个头文件即可

https://gitee.com/yuanfeng1897/cpp-httplib

2、示例,如下代码所示:

版本一:

#include "httplib.h"
#include 
#include 
using namespace std;
using namespace httplib;
class httpService {
private:
  std::thread work_thread_;
  Server svr_;

public:
  httpService();
  ~httpService();

  void work();
  void start();
  void creatConnect();
  static void ev_handler(const Request &req, Response &http_res);
};

httpService::httpService() {
  int port = 1234;
  string host = "localhost";
  svr_.set_keep_alive_max_count(5);
  svr_.set_keep_alive_timeout(10);
  svr_.bind_to_port(host.c_str(), port);
}

httpService::~httpService() {}

void httpService::ev_handler(const Request &req, Response &http_res) {
  http_res.set_content("hello world", "text/html");
}
void httpService::work() {
  svr_.Get("/", this->ev_handler);
  svr_.listen_after_bind();
}

void httpService::start() {
  work_thread_ = std::thread(&httpService::work, this);
  work_thread_.detach();
}

int main() {
  httpService http_svr;
  http_svr.start();
  while (1)
  {
    /* code */
  }
  
  return 0;
}

注意:主函数必须加whiile(1)循环进行阻塞,否则类对象马上被析构,主线程的资源被销毁,子线程(也就是请求命令的线程)无法工作。

3、另外一个版本:

#include "httplib.h"
#include 
#include 
using namespace std;
using namespace httplib;
class httpService {
private:
  std::thread work1_thread_;
  bool listening_;

public:
  Server svr_;

public:
  httpService();
  ~httpService();

  void work1();
  // void work2();
  void start();
  void stop();
  static void ev_handler1(const Request &req, Response &http_res);
  static void ev_handler2(const Request &req, Response &http_res);
};

httpService::httpService() {
  listening_ = false;
  int port = 1234;
  string host = "localhost";
  svr_.set_keep_alive_max_count(5);
  svr_.set_keep_alive_timeout(10);
  svr_.bind_to_port(host.c_str(), port);
}

httpService::~httpService() {}

void httpService::ev_handler1(const Request &req, Response &http_res) {
  http_res.set_content("path1", "text/html");
}
void httpService::ev_handler2(const Request &req, Response &http_res) {
  http_res.set_content("path2", "text/html");
}
void httpService::work1() {
  this->listening_ = true;
  svr_.Get("/path1", this->ev_handler1);
  svr_.Get("/path2", this->ev_handler2);
  svr_.listen_after_bind();
}

void httpService::start() {
  work1_thread_ = std::thread(&httpService::work1, this);
  work1_thread_.detach();
}

void httpService::stop() { this->listening_ = false; }

int main() {
  httpService http_svr;
  http_svr.start();
  cout << "hello world!" << endl;
  while (1) {
    /* code */
  }

  return 0;
}

你可能感兴趣的:(http,网络协议,网络,c++)