C++ Poco库安装

C++ Poco库安装与使用

poco官网:

https://pocoproject.org/

下载poco基础版

解压

tar zxvf poco-1.12.4.tar.gz

进入poco-1.12.4目录

cd poco-1.12.4

安装(注意cmake版本,需3.5以上)

./configure --no-tests --no-samples
cd build
cmake .. && make

如果cmake版本过低

卸载

yum -y remove cmake

cmake官网 https://cmake.org/ 下载最新安装包

解压

tar zxvf cmake-3.27.7.tar.gz

安装依赖

yum -y install openssl-devel

安装cmake

cd cmake-3.27.7
./configure
make && make install

使用示例:

实现了一个简单的多线程web服务器,为单个HTML页面提供服务,使用Foundation, Net和Util库,生成的网页在8080端口:

#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Util/ServerApplication.h"
#include <iostream>

using namespace Poco;
using namespace Poco::Net;
using namespace Poco::Util;

class HelloRequestHandler: public HTTPRequestHandler
{
    void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
    {
        Application& app = Application::instance();
        app.logger().information("Request from %s", request.clientAddress().toString());

        response.setChunkedTransferEncoding(true);
        response.setContentType("text/html");

        response.send()
            << "<html>"
            << "<head><title>Hello</title></head>"
            << "<body><h1>Hello from the POCO Web Server</h1></body>"
            << "</html>";
    }
};

class HelloRequestHandlerFactory: public HTTPRequestHandlerFactory
{
    HTTPRequestHandler* createRequestHandler(const HTTPServerRequest&)
    {
        return new HelloRequestHandler;
    }
};

class WebServerApp: public ServerApplication
{
    void initialize(Application& self)
    {
        loadConfiguration();
        ServerApplication::initialize(self);
    }

    int main(const std::vector<std::string>&)
    {
        UInt16 port = static_cast<UInt16>(config().getUInt("port", 8080));

        HTTPServer srv(new HelloRequestHandlerFactory, port);
        srv.start();
        logger().information("HTTP Server started on port %hu.", port);
        waitForTerminationRequest();
        logger().information("Stopping HTTP Server...");
        srv.stop();

        return Application::EXIT_OK;
    }
};

POCO_SERVER_MAIN(WebServerApp)

编译运行:

g++ -o main main.cpp -lPocoFoundation -lPocoNet -lPocoUtil  && ./main
posted @ 2023-10-15 16:41  洋綮  阅读(657)  评论(0)    收藏  举报