文章目录
1. Poco库介绍
Poco库是强大的的跨平台C++库,可以用来编写多平台的网络应用程序。
地址:https://pocoproject.org/
Poco可以用来做:
1.类型和字节序操作
2.错误处理和调试
3.内存管理
4.字符串和文本的格式化
5.平台和环境的操作和处理
6.随机数生成和各种哈希算法
7.时间和日期处理
8.文件操作系统处理
9.通知和事件
10.各种流处理
11.日志操作
12.动态的库操作
13.进程管理
14.url和uuid的生成和操作
15.XML和Json文件操作
16.网络编程
17.客户端程序和网络程序的编写
18.文件系统的支持和配置
19.日志系统的配置
2. Poco库配置
项目地址:https://github.com/pocoproject/poco/tree/master
编译过程如下:
cd poco
mkdir cmake-build
// 进入build并编译
cd cmake-build
cmake ..
// 生成lib
cmake --build . --config Release
// 安装
cmake --build . --target install
编译过程:
安装完成后生成dll和lib文件,需要用到的目录如下:
3. 示例程序
调用官方提供的示例。
实现了一个简单的多线程web服务器,为单个HTML页面提供服务。它使用Foundation, Net和Util库,并显示以下特性:
- 跨平台-代码将在所有支持的平台上工作,包括Linux, macOS和Windows。
- 日志记录
- Net库中的HTTP框架。
- 在Util库中支持服务器应用程序,包括配置文件处理。
#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)
将对应的include和lib放入工程目录下,然后配置工程参数,运行即可。
生成的网页在8080端口。
但是有这样一个问题:
等待解决。
以上。