microsoft / cpprestsdk

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.
Other
7.89k stars 1.64k forks source link

Server Sent Events (SSE) client #1027

Open salasjad opened 5 years ago

salasjad commented 5 years ago

Hi, I would like to know if there is any kind of support for Server Sent Events in cpprestsdk? I have a function eventGet() that will send a HTTP request and get a response from the server. However, the function is only able to get the first response message and then just wait. Any idea how this function can be used to read multiple responses from the server?

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;
         }
    ...
    }
}
fabriciolelis commented 5 years ago

@salasjad I'm trying to use your example but I've some problems. I need to read SSE events too. Can you help me?