我想知道cpprestsdk中是否对服务器发送事件有任何支持?我有一个函数eventGet(),它将发送HTTP请求并从服务器获取响应。但是,该函数只能获取第一个事件,然后才等待。
您知道如何使用此功能从服务器读取多个事件吗?
pplx::task<std::shared_ptr<Object>> MyApi::eventsGet()
{
std::shared_ptr<ApiConfiguration> apiConfiguration( m_ApiClient->getConfiguration());
utility::string_t path = utility::conversions::to_string_t("/Events");
std::map<utility::string_t, utility::string_t> queryParams;
std::map<utility::string_t, utility::string_t> headerParams( apiConfiguration->getDefaultHeaders());
std::map<utility::string_t, utility::string_t> formParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> fileParams;
std::unordered_set<utility::string_t> responseHttpContentTypes;
responseHttpContentTypes.insert( utility::conversions::to_string_t("text/event-stream"));
utility::string_t responseHttpContentType;
headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType;
std::unordered_set<utility::string_t> consumeHttpContentTypes;
std::shared_ptr<IHttpBody> httpBody;
utility::string_t requestHttpContentType;
return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams,
httpBody, headerParams, formParams, fileParams, requestHttpContentType)
.then([=](web::http::http_response response)
{
auto stream = response.body();
Concurrency::streams::container_buffer<std::string> line;
stream.read_line(line).then([line](size_t bytesRead)->size_t
{
const std::string &readText = line.collection();
std::cout << readText << std::endl;
return bytesRead;
}
...
}
}
我试图在eventGet()函数内添加一个while循环,以获取每次迭代的response.body()。然后readText
正确地获取了第一个事件数据,但是当发生新事件时,此后打印出空行。
while (true)
{
auto stream = response.body();
Concurrency::streams::container_buffer<std::string> line;
stream.read_line(line).then([line](size_t bytesRead) -> size_t
{
const std::string &readText = line.collection();
std::cout << readText.c_str() << std::endl;
return bytesRead;
});
}