如何:使用非同步資料流 (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();
}