1.简介
POCO C++ Libraries 提供一套 C++ 的类库用以开发基于网络的可移植的应用程序,它提供了许多模块,包括网络编程、文件系统访问、线程和并发、数据库访问、XML处理、配置管理、日志记录等功能。Poco库的设计目标是易于使用、高度可定制和可扩展。
包含4个核心库及一些附加库. 这4个核心模块是: Foundation, XML, Util 和 Net:
- Foundation:提供基本功能,如线程、时间、内存管理、流、字符串等。
- XML:提供XML解析和生成功能。
- Util:提供配置文件处理、命令行参数解析等实用功能。
- Net:提供网络编程功能,包括TCP/IP协议、HTTP服务器和客户端、SMTP客户端等。
还有一些其他模块:
- JSON:提供JSON解析和生成功能。
- Database:提供数据库访问抽象层,支持多种数据库。
- Crypto:提供加密和哈希算法。
- NetSSL:提供SSL/TLS加密的网络通信功能。
- Data:提供访问不同SQL数据库的一致性接口。
- Zip:提供ZIP文件处理功能。
2.环境搭建
下载地址:https://github.com/pocoproject/poco
注意:这里下载的编译器支持C++11的版本,根据自己的编译器来下载版本。
下载完成,进行解压,然后使用cmake编译。
configure->Generate->Open Project
生成库如下图所示:
拷贝头文件和lib、dll目录到demo程序,如下图拷贝Zip模块的头文件,其他模块同样操作。
拷贝完成后如下图所示。
配置visual studio环境,请看本专栏前面章节,主要配置include和lib目录,不再一一赘述。
3.代码示例
json解析示例。
#include "Poco/JSON/Parser.h"
#include "Poco/JSON/ParseHandler.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/Environment.h"
#include "Poco/Path.h"
#include "Poco/File.h"
#include "Poco/FileStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Stopwatch.h"
#include <iostream>
#include <iomanip>int main(int argc, char** argv)
{/* 解析json & 从文件中解析json */std::string jsonString = R"({"name": "John", "age": 30, "city": "New York"})";// 创建 JSON 解析器Poco::JSON::Parser parser;Poco::Dynamic::Var result;try {// 解析 JSON 字符串result = parser.parse(jsonString);}catch (const Poco::Exception& ex) {std::cerr << "JSON parsing error: " << ex.displayText() << std::endl;return 1;}// 将解析结果转换为 Poco::JSON::Object 类型Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>();// 获取和操作 JSON 对象中的值std::string name = object->getValue<std::string>("name");int age = object->getValue<int>("age");std::string city = object->getValue<std::string>("city");// 打印结果std::cout << "Name: " << name << std::endl;std::cout << "Age: " << age << std::endl;std::cout << "City: " << city << std::endl;/* 生成json & 写入到json文件 */// 创建 JSON 对象Poco::JSON::Object jsonObject;// 添加键值对jsonObject.set("name", "John");jsonObject.set("age", 30);jsonObject.set("city", "New York");// 将 JSON 对象转换为字符串std::ostringstream oss;Poco::JSON::Stringifier::stringify(jsonObject, oss);std::string jsonString2 = oss.str();// 打印生成的 JSON 字符串std::cout << jsonString2 << std::endl;return 0;
}
httpserver示例。
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Timestamp.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/Exception.h"
#include "Poco/ThreadPool.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include <iostream>using Poco::Net::ServerSocket;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPServerParams;
using Poco::Timestamp;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::ThreadPool;
using Poco::Util::ServerApplication;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;class TimeRequestHandler : public HTTPRequestHandler/// Return a HTML document with the current date and time.
{
public:TimeRequestHandler(const std::string& format) :_format(format){}void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response){Application& app = Application::instance();app.logger().information("Request from " + request.clientAddress().toString());Timestamp now;std::string dt(DateTimeFormatter::format(now, _format));response.setChunkedTransferEncoding(true);response.setContentType("text/html");std::ostream& ostr = response.send();ostr << "<html><head><title>HTTPTimeServer powered by POCO C++ Libraries</title>";ostr << "<meta http-equiv=\"refresh\" content=\"1\"></head>";ostr << "<body><p style=\"text-align: center; font-size: 48px;\">";ostr << dt;ostr << "</p></body></html>";}private:std::string _format;
};class TimeRequestHandlerFactory : public HTTPRequestHandlerFactory
{
public:TimeRequestHandlerFactory(const std::string& format) :_format(format){}HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request){if (request.getURI() == "/")return new TimeRequestHandler(_format);elsereturn 0;}private:std::string _format;
};class HTTPTimeServer : public Poco::Util::ServerApplication
{
public:HTTPTimeServer() : _helpRequested(false){}~HTTPTimeServer(){}protected:void initialize(Application& self){loadConfiguration(); // load default configuration files, if presentServerApplication::initialize(self);}void uninitialize(){ServerApplication::uninitialize();}void defineOptions(OptionSet& options){ServerApplication::defineOptions(options);options.addOption(Option("help", "h", "display help information on command line arguments").required(false).repeatable(false));}void handleOption(const std::string& name, const std::string& value){ServerApplication::handleOption(name, value);if (name == "help")_helpRequested = true;}void displayHelp(){HelpFormatter helpFormatter(options());helpFormatter.setCommand(commandName());helpFormatter.setUsage("OPTIONS");helpFormatter.setHeader("A web server that serves the current date and time.");helpFormatter.format(std::cout);}int main(const std::vector<std::string>& args){if (_helpRequested){displayHelp();}else{// get parameters from configuration fileunsigned short port = (unsigned short)config().getInt("HTTPTimeServer.port", 9980);std::string format(config().getString("HTTPTimeServer.format", DateTimeFormat::SORTABLE_FORMAT));int maxQueued = config().getInt("HTTPTimeServer.maxQueued", 100);int maxThreads = config().getInt("HTTPTimeServer.maxThreads", 16);ThreadPool::defaultPool().addCapacity(maxThreads);HTTPServerParams* pParams = new HTTPServerParams;pParams->setMaxQueued(maxQueued);pParams->setMaxThreads(maxThreads);// set-up a server socketServerSocket svs(port);// set-up a HTTPServer instanceHTTPServer srv(new TimeRequestHandlerFactory(format), svs, pParams);// start the HTTPServersrv.start();// wait for CTRL-C or killwaitForTerminationRequest();// Stop the HTTPServersrv.stop();}return Application::EXIT_OK;}private:bool _helpRequested;
};int main(int argc, char** argv)
{HTTPTimeServer app;return app.run(argc, argv);
}
TCPserver 示例。
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/NumberParser.h"
#include "Poco/Logger.h"
#include "Poco/Process.h"
#include "Poco/NamedEvent.h"
#include <iostream>using Poco::Net::TCPServer;
using Poco::Net::TCPServerConnectionFilter;
using Poco::Net::TCPServerConnection;
using Poco::Net::TCPServerConnectionFactory;
using Poco::Net::TCPServerConnectionFactoryImpl;
using Poco::Net::StreamSocket;
using Poco::UInt16;
using Poco::NumberParser;
using Poco::Logger;
using Poco::Event;
using Poco::NamedEvent;
using Poco::Process;
using Poco::ProcessImpl;
using Poco::Exception;namespace
{class ClientConnection: public TCPServerConnection{public:ClientConnection(const StreamSocket& s): TCPServerConnection(s){}void run(){StreamSocket& ss = socket();try{char buffer[256];int n = ss.receiveBytes(buffer, sizeof(buffer));while (n > 0){std::cout << "Received " << n << " bytes:" << std::endl;std::string msg;Logger::formatDump(msg, buffer, n);std::cout << msg << std::endl;n = ss.receiveBytes(buffer, sizeof(buffer));}}catch (Exception& exc){std::cerr << "ClientConnection: " << exc.displayText() << std::endl;}}};typedef TCPServerConnectionFactoryImpl<ClientConnection> TCPFactory;
#if defined(POCO_OS_FAMILY_WINDOWS)NamedEvent terminator(ProcessImpl::terminationEventName(Process::id()));
#elseEvent terminator;
#endif
}int main(int argc, char** argv)
{try{Poco::UInt16 port = NumberParser::parse((argc > 1) ? argv[1] : "2001");TCPServer srv(new TCPFactory(), port);srv.start();std::cout << "TCP server listening on port " << port << '.'<< std::endl << "Press Ctrl-C to quit." << std::endl;terminator.wait();}catch (Exception& exc){std::cerr << exc.displayText() << std::endl;return 1;}return 0;
}
4.更多推荐
libVLC 专栏介绍-CSDN博客
Qt+FFmpeg+opengl从零制作视频播放器-1.项目介绍_qt opengl视频播放器-CSDN博客
QCharts -1.概述-CSDN博客
网络库-libevent介绍
网络库-libcurl介绍