//下面程序取自 Poco 库的Net模块例子----HTTPServer  下面开始解析代码

#include "Poco/Net/HTTPServer.h"   //继承自TCPServer 实现了一个完整的HTTP多线程服务器
#include "Poco/Net/HTTPRequestHandler.h" //抽象基类类 被HttpServer所创建 用来处理Http的请求
#include "Poco/Net/HTTPRequestHandlerFactory.h" //HTTPRequestHandler的工厂 给予工厂设计模式
#include "Poco/Net/HTTPServerParams.h" //被用来指定httpserver以及HTTPRequestHandler的参数
#include "Poco/Net/HTTPServerRequest.h" //ServerRequest的抽象子类用来指定 服务器端的 http请求
#include "Poco/Net/HTTPServerResponse.h" //ServerResponse的抽象子类用来指定服务器端的http响应
#include "Poco/Net/ServerSocket.h" //提供了一个TCP服务器套接字接口
#include "Poco/Net/WebSocket.h" //这个类实现了RFC 6455 web套接字接口 专门针对web服务器用
#include "Poco/Net/NetException.h" //网络异常
#include "Poco/Util/ServerApplication.h" //Application的子类 所有服务器程序 包括 Reactor FTP HTTP等都用到 算是服务器的启动类
#include "Poco/Util/Option.h" //存储了命令行选项
#include "Poco/Util/OptionSet.h" //一个Opention对象的集合
#include "Poco/Util/HelpFormatter.h" //从OptionSet格式化帮助信息
#include "Poco/Format.h" //格式化函数的实现类似于 C的 sprintf函数 具体看文档
#include <iostream> using Poco::Net::ServerSocket;
using Poco::Net::WebSocket;
using Poco::Net::WebSocketException;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPServerParams;
using Poco::Timestamp;
using Poco::ThreadPool;
using Poco::Util::ServerApplication;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter; //////页面处理器 链接到来的时候 直接打印html内容
class PageRequestHandler: public HTTPRequestHandler
/// Return a HTML document with some JavaScript creating
/// a WebSocket connection.
{
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{ response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
std::ostream& ostr = response.send();
ostr << "<html>";
ostr << "<head>";
ostr << "<title>WebSocketServer</title>";
ostr << "<script type=\"text/javascript\">";
ostr << "function WebSocketTest()";
ostr << "{";
ostr << " if (\"WebSocket\" in window)";
ostr << " {";
ostr << " var ws = new WebSocket(\"ws://" << request.serverAddress().toString() << "/ws\");";
ostr << " ws.onopen = function()";
ostr << " {";
ostr << " ws.send(\"Hello, world!\");";
ostr << " };";
ostr << " ws.onmessage = function(evt)";
ostr << " { ";
ostr << " var msg = evt.data;";
ostr << " alert(\"Message received: \" + msg);";
ostr << " ws.close();";
ostr << " };";
ostr << " ws.onclose = function()";
ostr << " { ";
ostr << " alert(\"WebSocket closed.\");";
ostr << " };";
ostr << " }";
ostr << " else";
ostr << " {";
ostr << " alert(\"This browser does not support WebSockets.\");";
ostr << " }";
ostr << "}";
ostr << "</script>";
ostr << "</head>";
ostr << "<body>";
ostr << " <h1>WebSocket Server</h1>";
ostr << " <p><a href=\"javascript:WebSocketTest()\">Run WebSocket Script</a></p>";
ostr << "</body>";
ostr << "</html>";
}
}; /////////http请求处理器 1
class WebSocketRequestHandler: public HTTPRequestHandler
/// Handle a WebSocket connection.
{
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
Application& app = Application::instance();
try
{
WebSocket ws(request, response);
app.logger().information("WebSocket connection established.");
char buffer[];
int flags;
int n;
do
{
n = ws.receiveFrame(buffer, sizeof(buffer), flags);
app.logger().information(Poco::format("Frame received (length=%d, flags=0x%x).", n, unsigned(flags)));
ws.sendFrame(buffer, n, flags);
}
while (n > || (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
app.logger().information("WebSocket connection closed.");
}
catch (WebSocketException& exc)
{
app.logger().log(exc);
switch (exc.code())
{
case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
// fallthrough
case WebSocket::WS_ERR_NO_HANDSHAKE:
case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
response.setContentLength();
response.send();
break;
}
}
}
}; //HTTP请求处理器工厂
class RequestHandlerFactory: public HTTPRequestHandlerFactory
{
public:
HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) //覆盖方法
{
Application& app = Application::instance();
app.logger().information("Request from "
+ request.clientAddress().toString()
+ ": "
+ request.getMethod()
+ " "
+ request.getURI()
+ " "
+ request.getVersion());

//打印所有链接请求
for (HTTPServerRequest::ConstIterator it = request.begin(); it != request.end(); ++it)
{
app.logger().information(it->first + ": " + it->second);
}
//可以选择输出html页面 或者不输出 通过http请求参数
if(request.find("Upgrade") != request.end() && request["Upgrade"] == "websocket")
return new WebSocketRequestHandler;
else
return new PageRequestHandler;
}
}; //////////网络应用程序的启动器 都是ServerApplication
class WebSocketServer: public Poco::Util::ServerApplication
{
public:
WebSocketServer(): _helpRequested(false)
{
} ~WebSocketServer()
{
} protected:
///再启动的时候先调用
void initialize(Application& self)
{
loadConfiguration(); // load default configuration files, if present
ServerApplication::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 sample HTTP server supporting the WebSocket protocol.");
helpFormatter.format(std::cout);
}
//在初始化完毕之后调用
int main(const std::vector<std::string>& args)
{
if (_helpRequested)
{
displayHelp();
}
else
{
// get parameters from configuration file
//从配置文件中获取端口
unsigned short port = (unsigned short) config().getInt("WebSocketServer.port", ); // 安装一个ServerSocket
ServerSocket svs(port);
// s安装一个HttpServer实例 并且传递 请求处理器工厂 和一个HttpServerParams对象
HTTPServer srv(new RequestHandlerFactory, svs, new HTTPServerParams);
// 启动服务器
srv.start();
// 等待kill 或者控制台CTRL+C
waitForTerminationRequest();
// 停止HTTP服务器
srv.stop();
}
return Application::EXIT_OK; //返回正常退出状态
} private:
bool _helpRequested;
}; //启动web 服务器
POCO_SERVER_MAIN(WebSocketServer)

Poco C++库网络模块例子解析2-------HttpServer的更多相关文章

  1. Poco库网络模块例子解析1-------字典查询

    Poco的网络模块在Poco::Net名字空间下定义   下面是字典例子解析 #include "Poco/Net/StreamSocket.h" //流式套接字 #include ...

  2. POCO文档翻译:POCO C++库入门指南

    内容目录 介绍 Foundation库 XML库 Util库 Net库 将这些东西组合到一起 介绍 POCO C++库是一组开源C++类库的集合,它们简化及加速了用C++来开发以网络功能为核心的可移植 ...

  3. POCO C++库学习和分析——任务

    1.任务的定义 任务虽然在Poco::Foundation库的目录中被单独划出来,其实可以被看成线程的应用,放在线程章节.首先来看一下Poco中对任务的描述: *task主要应用在GUI和Sever程 ...

  4. iOS5系统API和5个开源库的JSON解析速度测试

    iOS5系统API和5个开源库的JSON解析速度测试 iOS5新增了JSON解析的API,我们将其和其他五个开源的JSON解析库进行了解析速度的测试,下面是测试的结果和工程代码附件. 我们选择的测试对 ...

  5. Tensorflow-hub[例子解析2]

    接Tensorflow-hub[例子解析1]. 3 基于文本词向量的例子 3.1 创建Module 可以从Tensorflow-hub[例子解析1].中看出,hub相对之前减少了更多的工作量. 首先, ...

  6. Generator函数执行器-co函数库源码解析

    一.co函数是什么 co 函数库是著名程序员 TJ Holowaychuk 于2013年6月发布的一个小工具,用于 Generator 函数的自动执行.短小精悍只有短短200余行,就可以免去手动编写G ...

  7. java_面试_02_Java面试题库及答案解析

    二.参考资料 1.Java面试题库及答案解析

  8. Android常用库源码解析

    图片加载框架比较 共同优点 都对多级缓存.线程池.缓存算法做了处理 自适应程度高,根据系统性能初始化缓存配置.系统信息变更后动态调整策略.比如根据 CPU 核数确定最大并发数,根据可用内存确定内存缓存 ...

  9. Java字节码例子解析

    举个简单的例子: public class Hello {     public static void main(String[] args) {         String string1 = ...

随机推荐

  1. Master Nginx(4) - Nginx as a Reverse Proxy

    Introduction to reverse proxying the proxy module legacy servers with cookies the upstream module ke ...

  2. Apk修改利器:ApkToolkit v2.1

    作 者: Mzucore 时 间: 2013-05-10, 17:18:23 链 接: http://www.unpack.cn/thread-93058-1-1.html 下载地址:http://b ...

  3. XML常用颜色值

    <?xml version="1.0" encoding="utf-8" ?> <resources> <color name=& ...

  4. visualbox使用(二)

    1.安装VirtualBox的[增强功能]2.VirtualBox的[设备]->[共享文件夹],添加固定分配,如D:\Java, 名称Java3.执行如下命令#cd /mnt#mkdir w_j ...

  5. Hacking Secret Ciphers with Python翻译序言

    马上就要下班,一直想做点什么,学点什么,但是似乎从未着手. 是的,我想学习Hacking,或许很多人都想学,但是诸多的大牛说,这个得有基础,万丈高楼平地起,我做过那么一点点的密码分析,加上某些地方有小 ...

  6. C++之内部类(嵌套类)与外部类及友元

    本人能力.精力有限,所言所感都基于自身的实践和有限的阅读.查阅,如有错误,欢迎拍砖,敬请赐教——博客园:钱智慧. 先上代码: class Outer { public: Outer(){m_outer ...

  7. 韦东山yy公开课笔记(2)--汇编,段,栈,重定位/链接地址,位置无关吗

    1. 要不要学习汇编 可以只懂一点,工作中基本不用,一旦用就是出了大问题 ldr : load 读内存 ldr r0, [r1]  : r1里存放的是地址值, 去这个地址读取4字节的内容,存入r0 s ...

  8. BeanPostProcessor 的使用,实现在对象初始化之前或者之后对对象进行操作

    import java.lang.reflect.Field; import org.springframework.beans.BeansException; import org.springfr ...

  9. ndk-gdb of NDK r9d modified to *always* debug the ":remote"-process of your app

    https://gist.github.com/TomTasche/9690186 ndk-gdb of NDK r9d modified to *always* debug the ":r ...

  10. ios开发中如何实现软件版本更新

    苹果给了我们一个接口,能根据应用id请求一些关于应用的信息.我们可以根据返回的信息,来判断版本是否和应用的版本一致,如果不一致,那么就出现新的版本了.这时,就需要向用户提醒有新的版本,需要更新.具体步 ...