如何:使用异步流 (C++ REST SDK)

C++ REST SDK (codename "Casablanca") 提供流功能,可让你更轻松地使用 TCP 套接字、磁盘上的文件和内存。 C++ REST SDK 流类似于 C++ 标准库提供的功能,不同之处是 C++ REST SDK 版本利用异步。 该库对可能起阻止作用的 I/O 操作返回 pplx::task,而不是直接返回值。 此页显示两个示例。 第一个示例显示如何使用 STL 容器和原始内存向流写入数据和从流读取数据。 第二个示例创建 HTTP GET 请求,并将其部分响应流输出到控制台中。

警告

本主题包含有关 C++ REST SDK 1.0 (codename "Casablanca") 的信息。如果你正在从 Codeplex Casablanca 网页 使用更高版本,则使用 http://casablanca.codeplex.com/documentation 上的本地文档。

在这些示例之后,有一个更完整的示例显示 #include 和 using 语句。

将流与 STL 容器和原始内存一起使用

此示例演示如何使用 STL 容器和原始内存向流读取数据和从流写入数据。

// Shows how to read from and write to a stream with an STL container or raw pointer. 
void ReadWriteStream(istream inStream, ostream outStream)
{
    // Write a string to the stream.
    std::string strData("test string to write\n");
    container_buffer<std::string> outStringBuffer(std::move(strData));
    outStream.write(outStringBuffer, outStringBuffer.collection().size()).then([](size_t bytesWritten)
    {
        // Perform actions here once the string has been written...
    });

    // Read a line from the stream into a string.
    container_buffer<std::string> inStringBuffer;
    inStream.read_line(inStringBuffer).then([inStringBuffer](size_t bytesRead)
    {
        const std::string &line = inStringBuffer.collection();

        // Perform actions here after reading line into a string...
    });

    // Write data from a raw chunk of contiguous memory to the stream. 
    // The raw data must stay alive until write operation has finished. 
    // In this case we will place on the heap to avoid any issues. 
    const size_t rawDataSize = 8;
    unsigned char* rawData = new unsigned char[rawDataSize];
    memcpy(&rawData[0], "raw data", rawDataSize);
    rawptr_buffer<unsigned char> rawOutBuffer(rawData, rawDataSize, std::ios::in);
    outStream.write(rawOutBuffer, rawDataSize).then([rawData](size_t bytesWritten)
    {
        delete []rawData;

        // Perform actions here once the string as been written...
    });
}

访问 HTTP 响应流

以下是使用 web::http::http_response::body 方法检索可从其中读取数据的 concurrency::streams::istream 对象的方法。 为简单起见,此示例仅将响应的前几个字符传输到控制台中。 有关检索服务器响应但不使用响应流的更基础的版本,请参阅如何:连接到 HTTP 服务器

// Creates an HTTP request and prints part of its response stream.
pplx::task<void> HTTPStreamingAsync()
{
    http_client client(L"https://www.fourthcoffee.com");

    return client.request(methods::GET).then([](http_response response)
    {
        if(response.status_code() != status_codes::OK)
        {
            // Handle error cases... 
            return pplx::task_from_result();
        }

        // Perform actions here reading from the response stream... 
        // In this example, we print the first 15 characters of the response to the console.
        istream bodyStream = response.body();
        container_buffer<std::string> inStringBuffer;
        return bodyStream.read(inStringBuffer, 15).then([inStringBuffer](size_t bytesRead)
        {
            const std::string &text = inStringBuffer.collection();

            // For demonstration, convert the response text to a wide-character string.
            std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf16conv;
            std::wostringstream ss;
            ss << utf16conv.from_bytes(text.c_str()) << std::endl;
            std::wcout << ss.str();
        });
    });

    /* Output:
    <!DOCTYPE html>
    */
}

完整示例

以下是完整示例。

#include <codecvt>
#include <containerstream.h>
#include <http_client.h>
#include <iostream>
#include <producerconsumerstream.h>
#include <rawptrstream.h>

using namespace concurrency;
using namespace concurrency::streams;
using namespace web::http;
using namespace web::http::client;

// Shows how to read from and write to a stream with an STL container or raw pointer. 
void ReadWriteStream(istream inStream, ostream outStream)
{
    // Write a string to the stream.
    std::string strData("test string to write\n");
    container_buffer<std::string> outStringBuffer(std::move(strData));
    outStream.write(outStringBuffer, outStringBuffer.collection().size()).then([](size_t bytesWritten)
    {
        // Perform actions here once the string has been written...
    });

    // Read a line from the stream into a string.
    container_buffer<std::string> inStringBuffer;
    inStream.read_line(inStringBuffer).then([inStringBuffer](size_t bytesRead)
    {
        const std::string &line = inStringBuffer.collection();

        // Perform actions here after reading line into a string...
    });

    // Write data from a raw chunk of contiguous memory to the stream. 
    // The raw data must stay alive until write operation has finished. 
    // In this case we will place on the heap to avoid any issues. 
    const size_t rawDataSize = 8;
    unsigned char* rawData = new unsigned char[rawDataSize];
    memcpy(&rawData[0], "raw data", rawDataSize);
    rawptr_buffer<unsigned char> rawOutBuffer(rawData, rawDataSize, std::ios::in);
    outStream.write(rawOutBuffer, rawDataSize).then([rawData](size_t bytesWritten)
    {
        delete []rawData;

        // Perform actions here once the string as been written...
    });
}

// Creates an HTTP request and prints part of its response stream.
pplx::task<void> HTTPStreamingAsync()
{
    http_client client(L"https://www.fourthcoffee.com");

    return client.request(methods::GET).then([](http_response response)
    {
        if(response.status_code() != status_codes::OK)
        {
            // Handle error cases... 
            return pplx::task_from_result();
        }

        // Perform actions here reading from the response stream... 
        // In this example, we print the first 15 characters of the response to the console.
        istream bodyStream = response.body();
        container_buffer<std::string> inStringBuffer;
        return bodyStream.read(inStringBuffer, 15).then([inStringBuffer](size_t bytesRead)
        {
            const std::string &text = inStringBuffer.collection();

            // For demonstration, convert the response text to a wide-character string.
            std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf16conv;
            std::wostringstream ss;
            ss << utf16conv.from_bytes(text.c_str()) << std::endl;
            std::wcout << ss.str();
        });
    });

    /* Output:
    <!DOCTYPE html>
    */
}

int wmain()
{
    // This example uses the task::wait method to ensure that async operations complete before the app exits.  
    // In most apps, you typically don�t wait for async operations to complete.

    streams::producer_consumer_buffer<uint8_t> buffer;
    //ReadWriteStream(buffer.create_istream(), buffer.create_ostream());

    HTTPStreamingAsync().wait();
}

请参见

其他资源

C++ REST SDK (Codename "Casablanca")