【问题标题】:How to detect when stream has been closed in POCO HTTPRequestHandler?如何检测 POCO HTTPRequestHandler 中的流何时关闭?
【发布时间】:2023-02-12 23:23:11
【问题描述】:

在我的应用程序中,我想使用 POCO 库通过 HTTP Web 服务器流式传输 jpg 图像,为此我在响应正文中使用 multipart/x-mixed-replace 内容类型。这意味着当 GET 请求到达 HTTP 服务器时,它会在单个 http 响应中连续向客户端分段发送图像。

当客户端关闭窗口时,流应该关闭并且请求处理程序应该返回。但我对 HTTPServerResponse.send() 流的问题是它只会在响应对象被销毁时被销毁,所以我不知道客户端何时离开,以及何时必须停止发送图像。

这就是代码的样子:

#pragma once    

#include <fstream>
#include <sstream>
#include <string>
#include "Poco/Net/HTTPRequestHandler.h"
    
class StreamHandler : public Poco::Net::HTTPRequestHandler {
 public:
    void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) override {
        std::ifstream imgFile("../../assets/imgs/random.jpg");
        std::stringstream ss{};
        ss << imgFile.rdbuf();
        std::string buf = ss.str();

        std::string boundary = "--BOUNDARY--";
        response.setVersion(request.getVersion());
        response.setStatus(Poco::Net::HTTPServerResponse::HTTP_OK);
        response.setChunkedTransferEncoding(false);
        response.setKeepAlive(false);
        response.setContentType("multipart/x-mixed-replace; boundary=" + boundary);
        response.set("Access-Control-Allow-Origin", "*");
        response.set("Connection", "Close");
        response.set("Cache-Control",
                     "no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, false");
        response.set("Pragma", "no-cache");
        std::ostream& ostr = response.send();

        while (true) { // <-- What is the stop condition?
            ostr << boundary << "\r\n";
            ostr << "Content-Type: image/jpeg\r\n"
                    "Content-Length: " +
                        std::to_string(buf.length()) + "\r\n\r\n";
            ostr << buf;
            ostr << "\r\n";
        }
    }
};

有没有办法检测客户是否离开?

PS:可能我想要Poco::Net::HTTPRequestHandler范围内的解决方案。我不想要任何需要打开另一个端口或仅将另一个第三方库用于流媒体的解决方案。例如,我已经在使用 nadjieb/cpp-mjpeg-streamer,它运行良好,但我想简化我的代码并仅依赖于 POCO。在较低级别的库中,我看到了使用以下策略的良好实现:

while (true) {
    if (res) {
        res = http_res_send_chunk(req, part_buf, part_len);
    } else {
        break;
    }
}

发送命令在成功的情况下返回一些正整数,如果发送函数失败则返回 0。但是,不幸的是,我无法用 POCO 复制它。任何想法如何解决这个问题?

【问题讨论】:

    标签: c++ http streaming poco-libraries multipart-mixed-replace


    【解决方案1】:

    我终于找到了解决方案并将其发布here。如果我的回答被接受,我会将这个问题标记为重复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多