从 POCO HTTPRequestHandler 访问其他线程或数据

Accessing other threads or data from POCO HTTPRequestHandler

我有一个 C++ 应用程序可以读取各种传感器,然后根据需要对它们进行操作。目前,传感器 运行 在它们自己的线程中并且有 get/set 方法来获取它们的值。

我正在尝试使用 POCO 库集成一个网络套接字服务器来显示传感器的状态。

如何将传感器信息导入 HTTPRequestHandler?

我应该使用 POCO::Application class 并将传感器和服务器定义为子系统吗?我应该采取另一种方法吗?

您可以从 HTTPRequestHandler 派生并覆盖 handleRequest() 并通过例如将对传感器信息对象的引用存储为 class 派生的成员来访问传感器信息来自 HTTPRequestHandler.

class SensorStateRequestHandler : public Poco::Net::HTTPRequestHandler
{
public:
    SensorStateRequestHandler(SensorInfo &sensorInfo)
        : sensorInfo_(sensorInfo)
    {}

    virtual void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override
    {
        // receive request websocket frame
        sensorInfo_.get_state(); // must be thread safe
        // send response websocket frame with sensor state
    }

private:
    sensorInfo &sensorInfo_;
};

查看 WebEventService in macchina.io 的实现方式 - 使用 Poco::Net::HTTPServer、WebSocket 和 Poco::NotificationQueue。

设计"in a nutshell"是pub/sub模式,客户端订阅通知,通过WebSocket接收; in-process subscriptions/notifications (using Poco events) are also supported. There is a single short-living thread (HTTP handler) launched at subscription time and the rest of communication is through WebSocket reactor-like 功能,因此性能和可扩展性相当不错(尽管有改进的空间,具体取决于目标平台)。

您可以考虑使用 macchina.io 本身(Apache 许可证)- 它基于 1.7.0 版本中的 POCO/OSP and targets the type of application you have. WebEvent functionality will be part of Poco::NetEx(计划于今年 9 月发布)。