派生自 development/c++

xuxiuxi
2019-03-08 118d5304c8744a3cb533164af6fbdc91229d6f3d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#ifndef HTTPSRVRETRECIEVE_H_XZL_201808171114
#define HTTPSRVRETRECIEVE_H_XZL_201808171114
 
#include "client_http.hpp"
#include "server_http.hpp"
 
// Added for the json-example
#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
 
// Added for the default_resource example
#include <algorithm>
#include <boost/filesystem.hpp>
#include <fstream>
#include <vector>
#include <basic/debug/Debug.h>
 
#ifdef HAVE_OPENSSL
#include "crypto.hpp"
#endif
 
using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;
using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>;
class HttpSrvRetRecieve
{
    using TASK_FUNCTION = std::function<std::string(std::string,unsigned short,std::string,std::shared_ptr<HttpServer::Response>&)>;
    using OTHER_FUNCTION = std::function<void(int)>;
public:
    HttpSrvRetRecieve(const std::string& ip,const unsigned short port,const std::size_t& threadPoolSize)
        :m_TASK_FUNCTION(nullptr)
    {
        m_server.config.address = ip;
        m_server.config.port = port;
        m_server.config.thread_pool_size = threadPoolSize;
    }
 
    int setInfo(const std::string& strInfo,const std::string& strType,TASK_FUNCTION f)
    {
        m_map_TASKFUNC[strInfo.substr(1,(strInfo.size()-2))] = f;
        m_server.resource[strInfo][strType] = [this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request)
        {
            std::string strInfo =  request->path;
            auto func = m_map_TASKFUNC[strInfo];
            if(func != nullptr){
                std::string strRet = func(request->remote_endpoint_address(),request->remote_endpoint_port(),request->content.string(),response);
                if(strRet.size() > 0){
                    DBG("strRet.size() > 0");
                    response->write(strRet);
                } else{
                    ERR("strRet.size() <= 0");
                }
            }else{
                std::cout << " func == nullptr " << std::endl;
            }
        };
        m_server.on_error = [](std::shared_ptr<HttpServer::Request> /*request*/, const SimpleWeb::error_code & /*ec*/)
        {};
    }
 
    int start()
    {
        m_server_thread = std::make_shared<std::thread>([&]() {
            // Start server
            m_server.start();
          });
        return 0;
    }
    int waitForShutDown()
    {
        m_server_thread->join();
    }
 
private:
    HttpServer m_server;
    TASK_FUNCTION m_TASK_FUNCTION;
    std::map<std::string,TASK_FUNCTION> m_map_TASKFUNC;
    std::shared_ptr<std::thread> m_server_thread;
};
#endif