首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >nghttp2:使用EventSource使用的服务器发送的事件

nghttp2:使用EventSource使用的服务器发送的事件
EN

Stack Overflow用户
提问于 2020-12-11 22:27:03
回答 1查看 245关注 0票数 0

我正在使用nghttp2实现一个REST服务器,它应该使用HTTP/2和服务器发送的事件(将由浏览器中的EventSource使用)。然而,基于这些示例,我并不清楚如何实现SSE。像在asio-sv.cc中一样使用res.push()似乎不是正确的方法。

什么才是正确的方法呢?我更喜欢使用nghttp2的C++应用程序接口,但是C应用程序接口也可以。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-15 10:48:18

是的,早在2018年我就做过类似的事情。文档相当稀疏:)。

首先,忽略response::push,因为这是HTTP2推送--它用于在客户端请求对象之前主动向客户端发送这些对象。我知道这听起来像是您需要的,但事实并非如此--典型的用例是主动发送CSS文件和一些图像以及最初请求的HTML页面。

关键是,无论何时用完要发送的数据,end()回调最终都必须返回NGHTTP2_ERR_DEFERRED。当您的应用程序以某种方式获得更多要发送的数据时,调用http::response::resume()

下面是一个简单的代码。将其构建为g++ -std=c++17 -Wall -O3 -ggdb clock.cpp -lssl -lcrypto -pthread -lnghttp2_asio -lspdlog -lfmt。请注意,现代浏览器不会在明文套接字上执行HTTP/2,因此您需要通过nghttpx -f '*,8080;no-tls' -b '::1,10080;;proto=h2'之类的东西对其进行反向代理。

代码语言:javascript
复制
#include <boost/asio/io_service.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/signals2.hpp>
#include <chrono>
#include <list>
#include <nghttp2/asio_http2_server.h>
#define SPDLOG_FMT_EXTERNAL
#include <spdlog/spdlog.h>
#include <thread>

using namespace nghttp2::asio_http2;
using namespace std::literals;

using Signal = boost::signals2::signal<void(const std::string& message)>;

class Client {
    const server::response& res;
    enum State {
        HasEvents,
        WaitingForEvents,
    };
    std::atomic<State> state;

    std::list<std::string> queue;
    mutable std::mutex mtx;
    boost::signals2::scoped_connection subscription;

    size_t send_chunk(uint8_t* destination, std::size_t len, uint32_t* data_flags [[maybe_unused]])
    {
        std::size_t written{0};
        std::lock_guard lock{mtx};
        if (state != HasEvents) throw std::logic_error{std::to_string(__LINE__)};
        while (!queue.empty()) {
            auto num = std::min(queue.front().size(), len - written);
            std::copy_n(queue.front().begin(), num, destination + written);
            written += num;
            if (num < queue.front().size()) {
                queue.front() = queue.front().substr(num);
                spdlog::debug("{} send_chunk: partial write", (void*)this);
                return written;
            }
            queue.pop_front();
            spdlog::debug("{} send_chunk: sent one event", (void*)this);
        }
        state = WaitingForEvents;
        return written;
    }

public:
    Client(const server::request& req, const server::response& res, Signal& signal)
    : res{res}
    , state{WaitingForEvents}
    , subscription{signal.connect([this](const auto& msg) {
        enqueue(msg);
    })}
    {
        spdlog::warn("{}: {} {} {}", (void*)this, boost::lexical_cast<std::string>(req.remote_endpoint()), req.method(), req.uri().raw_path);
        res.write_head(200, {{"content-type", {"text/event-stream", false}}});
    }

    void onClose(const uint32_t ec)
    {
        spdlog::error("{} onClose", (void*)this);
        subscription.disconnect();
    }

    ssize_t process(uint8_t* destination, std::size_t len, uint32_t* data_flags)
    {
        spdlog::trace("{} process", (void*)this);
        switch (state) {
        case HasEvents:
            return send_chunk(destination, len, data_flags);
        case WaitingForEvents:
            return NGHTTP2_ERR_DEFERRED;
        }
        __builtin_unreachable();
    }

    void enqueue(const std::string& what)
    {
        {
            std::lock_guard lock{mtx};
            queue.push_back("data: " + what + "\n\n");
        }
        state = HasEvents;
        res.resume();
    }
};

int main(int argc [[maybe_unused]], char** argv [[maybe_unused]])
{
    spdlog::set_level(spdlog::level::trace);

    Signal sig;
    std::thread timer{[&sig]() {
        for (int i = 0; /* forever */; ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds{666});
            spdlog::info("tick: {}", i);
            sig("ping #" + std::to_string(i));
        }
    }};

    server::http2 server;
    server.num_threads(4);

    server.handle("/events", [&sig](const server::request& req, const server::response& res) {
        auto client = std::make_shared<Client>(req, res, sig);

        res.on_close([client](const auto ec) {
            client->onClose(ec);
        });
        res.end([client](uint8_t* destination, std::size_t len, uint32_t* data_flags) {
            return client->process(destination, len, data_flags);
        });
    });

    server.handle("/", [](const auto& req, const auto& resp) {
        spdlog::warn("{} {} {}", boost::lexical_cast<std::string>(req.remote_endpoint()), req.method(), req.uri().raw_path);
        resp.write_head(200, {{"content-type", {"text/html", false}}});
        resp.end(R"(<html><head><title>nghttp2 event stream</title></head>
<body><h1>events</h1><ul id="x"></ul>
<script type="text/javascript">
const ev = new EventSource("/events");
ev.onmessage = function(event) {
  const li = document.createElement("li");
  li.textContent = event.data;
  document.getElementById("x").appendChild(li);
};
</script>
</body>
</html>)");
    });

    boost::system::error_code ec;
    if (server.listen_and_serve(ec, "::", "10080")) {
        return 1;
    }
    return 0;
}

我有种感觉,我的队列处理可能太复杂了。在通过curl进行测试时,我似乎从不会耗尽缓冲区空间。换句话说,即使客户机没有从套接字读取任何数据,库也会继续调用send_chunk,一次为我请求最多16kB的数据。真奇怪。当推送更多的数据时,我不知道它是如何工作的。

我的“真正的代码”曾经有第三个状态,Closed,但我认为通过on_close阻塞事件在这里就足够了。然而,如果客户端已经断开连接,但在析构函数被调用之前,我认为你永远不会想要进入send_chunk

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65253162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档