方法: 非同期ストリームを操作する (C++ REST SDK)
C++ REST SDK (コード名 "Casablanca") には、より簡単に TCP ソケット、ディスク上のファイル、メモリを使用できるようにするストリーム機能が用意されています。 C++ REST SDK のストリームは、C++ 標準ライブラリに用意されているストリームと類似しています。ただし、C++ REST SDK のバージョンでは非同期性を利用する点が異なります。 ライブラリは pplx::task を返しますが、ブロックする可能性がある I/O 操作については、値を直接返しません。 このページでは、2 つの例を紹介します。 最初の例では、STL コンテナーと生のメモリを使用してストリームに書き込む方法とストリームから読み取る方法を示します。 2 番目の例では、HTTP GET 要求を作成し、応答ストリームの一部をコンソールに出力します。
注意
このトピックでは、C++ REST SDK 1.0 (コード名 "Casablanca") について説明します。Codeplex の Casablanca の Web ページからそれ以降のバージョンを使用している場合は、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 オブジェクトを取得する方法を示します。 わかりやすくするために、この例では、応答の最初の数文字だけをコンソールに出力します。 サーバー応答を取得するが応答ストリームを使用しない、より基本的なバージョンについては、「How to: Connect to HTTP servers (方法: 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();
}