eidheim / Simple-Web-Server

A very simple, fast, multithreaded, platform independent HTTP and HTTPS server and client library implemented using C++11 and Boost.Asio. Created to be an easy way to make REST resources available from C++ applications.
MIT License
2.62k stars 758 forks source link

How to use HttpServer as a member variable? #95

Closed CKirsch87 closed 7 years ago

CKirsch87 commented 7 years ago

How can I use HttpServer as a member variable in my own class. The HttpServer should start if some event occurs and change its response to another event after starting. If I define a pointer of HttpServer and initialize it inside my class constructor I'm getting some curious compiler errors.

eidheim commented 7 years ago

This works if you use c++14:

#include "server_http.hpp"
#include <memory>

using namespace std;
using namespace SimpleWeb;

class Test {
public:
  unique_ptr<Server<HTTP>> server;

  void start() {
    server = make_unique<Server<HTTP>>(8080);

    server->resource["^/$"]["GET"] = [](auto response, auto request) {
      *response << "HTTP/1.1 200 OK\r\nContent-Length: " << 4 << "\r\n\r\n" << "test";
    };

    server->start();
  }
};

int main() {
  Test test;
  test.start();
}
CKirsch87 commented 7 years ago

Declaration, initialization and starting the server works fine. But now I would prefer to start the server in its own thread. To use boost::thread (like in the example) doesn't work. I'm getting an this error "error: ‘this’ was not captured for this lambda function". Is there a way to start the member server as a separate thread?

eidheim commented 7 years ago

Please google the errors you are getting. I do not have time to answer C++ related questions sorry:)

sunjunlishi commented 6 years ago

please use thread.join();