30
2014년 3월 C++ 클라우드 환경을 준비하다 C++ REST SDK 2.0 (Codename : Casablanca) Session #4

Session #4 C++ REST SDK 2.0 (Codename : Casablanca)download.microsoft.com/download/2/2/6/226239CC-017C-46DC... · 2018-10-13 · 2014년3월 C++ 클라우드환경을준비하다

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

2014년 3월C++ 클라우드 환경을 준비하다

C++ REST SDK 2.0 (Codename : Casablanca)

Session #4

Motivation : 재사용을 통한 생산성 향상

실행되는 언어

기계어

읽을 수 있는 언어

어셈블리어

함수 재사용

C언어

클래스 재사용

C++언어

바이너리 재사용

COM,DCOM

2

Motivation : 원격지 기능 사용

3

Motivation : 미들웨어

http://middleware.smile.fr/Concepts-des-moms-et-jms/Qu-est-ce-qu-un-middleware4

Motivation : WebService

http://msdn.microsoft.com/ko-kr/library/azure/jj554228.aspx5

Motivation : 도메인 지향 데이터 전송

http://www.programmableweb.com/news/3000-web-apis-trends-quickly-growing-directory/2011/03/08

http://superwebapps.dk/6

라이브러리 선택

http://realtimelogic.com/products/ajax/http://en.wikipedia.org/wiki/Cloud_computing#mediaviewer/File:Cloud_computing.svg

7

C++ REST SDK 특징

• 서버 애플리케이션 지원• IIS 호스팅/Azure/stand-alone 방식의 서버 애플리케이션 구현 가능

• 클라이언트 애플리케이션 지원• 통신 라이브러리, 파서, 직렬화 등 필수적인 라이브러리 셋의 모음

• 오픈 소스• http://casablanca.codeplex.com

• 크로스 플랫폼 (윈도우, 리눅스, OS X, iOS, 윈폰, WinRT…)

• 모던 C++• 최신 트렌드에 맞는 스타일의 코드 작성 가능• 간결하고 유지보수하기 쉬우며 생산성 높은 코드 작성 가능

• 비주얼 스튜디오의 지원

8

C++ REST SDK

9

NuGet

• 라이브러리 패키지 관리• 오픈소스 라이브러리 제공, 형상관리, 커뮤니티등 토털 에코시스템

• 15000여개 프로젝트, 11만 6천여개 프로젝트 패키지 관리

• 하루평균 약 23만건 정도의 프로젝트 다운로드

10

NuGet 호스팅

• Nexus : http://www.sonatype.com/nexus/nexus-pro-features

• Artifactory : http://www.jfrog.com/home/v_artifactorypro_features

• Inedo ProGet : http://inedo.com/proget/overview

• MyGET : http://www.myget.org

11

NuGet을 이용한 로컬 패키지 관리

12

http://www.cafex.com/wp-content/uploads/2012/09/demo_banner.png13

C++ REST SDK에 포함된 라이브러리Task

Programming

JSON Parser

Asynchronous

Streams

HTTP Client

HTTP Listener

Utility &

Helper

14

Architecture

Async File I/O

TimersBinary Serializers

JSONParser & Writer

Azure / IIS Host Windows 7 Host

Windows XP, Vista, 7, 8.x / Windows Phone 8.x / Linux / Mac OS X / iOS

IOCPPPLWinHTTP

HTTPClient & Listener

TCPClient & Listener

Web SocketsClient & Listener

Apps & Libraries

Azure Storage Windows LiveXboxLive

BingMaps

Foundation

Casablanca Lib

Service Host

Possible 3rd Party

Boost.Asio HTTP.sys

15

Task 클래스와 Continuations 패턴

task<T> taskObject_A([](){slow_operation_A()});taskObject_A.then([](T i) {

return slow_operation_B(i);});bool isDone = taskObject_A.is_done();taskObject_A.wait();T A_return_value = taskObject_A.get();

http://msdn.microsoft.com/en-us/library/windows/apps/jj160321.aspx 16

Join 패턴, Choice 패턴 구현

array<task<int>, 3> tasks = {create_task([]() -> int { return long_ret_1(); }),create_task([]() -> int { return middle_ret_2(); }),create_task([]() -> int { return short_ret_3(); })

};when_any(begin(tasks), end(tasks)).then([](pair<int, size_t> result){

// 결과값과 인덱스 반환. [3, 2]}).wait();when_all(begin(tasks), end(tasks)).then([](vector<int> results) {

// 결과값 반환. [1, 2, 3]}).wait();

17

문자열 처리

• 플랫폼마다 다른 문자열 방식 지원• utility::string_t, size64_t, char_t, istrinm_t, …

• URI(Uniform Resource Identifiers)• protocol : // server [: port] / path ? query # fragment • http://search.cpprestsdk.com:8080/search/total.jsp?id=1234&comment=rest#cosmos

• <->base64, <->utf8, <->utf16

18

URI 다루기

uri_builder b;b.set_scheme(U("http"));b.set_host(U("search.naver.com"));b.set_port(80);b.set_path(U("search.naver"));b.set_query(uri::encode_uri(U("query=a가1나")));

// http://search.naver.com:80/search.naver?query=a%EA%B0%801%EB%82%98

vector<string_t> paths = uri::split_path(u.to_string());map<string_t, string_t> querys = uri::split_query(u.to_string());

19

문자열 변환관련 유틸리티 함수 군

namespace Utility {namespace conversions{std::string __cdecl utf16_to_utf8(const utf16string &w);utf16string __cdecl utf8_to_utf16(const std::string &s);utf16string __cdecl usascii_to_utf16(const std::string &s);utf16string __cdecl latin1_to_utf16(const std::string &s);utf16string __cdecl default_code_page_to_utf16(const std::string &s);utility::string_t __cdecl to_string_t(std::string &&s);utility::string_t __cdecl to_string_t(utf16string &&s);utility::string_t __cdecl to_string_t(const std::string &s);utility::string_t __cdecl to_string_t(const utf16string &s);utf16string __cdecl to_utf16string(const std::string &value);utf16string __cdecl to_utf16string(utf16string value);std::string __cdecl to_utf8string(std::string value);std::string __cdecl to_utf8string(const utf16string &value);utility::string_t __cdecl to_base64(const std::vector<unsigned char>& data);utility::string_t __cdecl to_base64(uint64_t data);std::vector<unsigned char> __cdecl from_base64(const utility::string_t& str);template <typename Source> utility::string_t print_string(const Source &val)template <typename Target> Target scan_string(const utility::string_t &str)

}}

20

http_listener

var http = require('http');http.createServer(function (request, response) {response.writeHead(200, {'Content-Type': 'text/plain'});response.end('Hello World!');

}).listen(8080, '127.0.0.1');

task_status server() {http_listener listener(U("http://localhost:8080/test"));listener.support([&listener](http_request request)->void{

request.reply(status_codes::OK, L"Hello World");});listener.open().then([](){while (1) Sleep(10000);}).wait();listener.close().wait();

}21

http_client

task_status foo() {http_client client(U("http://se.naver.com/index.html"));return client.request(methods::GET).then([](http_response response) {

std::wcout << response.extract_string().get() << std::endl;}).wait();

}

int _tmain(int argc, _TCHAR* argv []) {foo();return 0;

}

22

http://www.cafex.com/wp-content/uploads/2012/09/demo_banner.png23

JSON

web::json::value v0 = web::json::value::null();web::json::value v1 = web::json::value::number(17);web::json::value v2 = web::json::value::number(3.1415);web::json::value v3 = web::json::value::boolean(true);web::json::value v4 = web::json::value::string(U("Hello Again!"));web::json::value v5 = web::json::value::object();web::json::value v6 = web::json::value::array();

24

field_map을 이용한 JSON 셋

web::json::value::field_map f;f.push_back(std::pair<web::json::value, web::json::value>

(web::json::value::string(U("name1")), web::json::value::number(1)));f.push_back(std::pair<web::json::value, web::json::value>

(web::json::value::string(U("name2")), web::json::value::string(U("hello"))));f.push_back(std::pair<web::json::value, web::json::value>

(web::json::value::string(U("name3")), web::json::value::boolean(U("true"))));f.push_back(std::pair<web::json::value, web::json::value>

(web::json::value::string(U("name4")), web::json::value::null()));web::json::value obj = web::json::value::object(f);std::wcout << obj.to_string() << std::endl;

출력값 :{ "name1" : 1, "name2" : "hello", "name3" : true, "name4" : null }

25

object를 직접 다루어 JSON 셋팅

web::json::value obj = web::json::value::object();obj[U("name1")] = web::json::value::string(U("hi there"));obj[U("name2")] = web::json::value::number(77);std::wcout << obj.to_string() << std::endl;

출력값 :{ "name1" : "hi there", "name2" : 77 }

26

as_* 함수를 이용하여 값 조회

web::json::value v1 = web::json::value::number(17);web::json::value v2 = web::json::value::number(3.1415);web::json::value v3 = web::json::value::boolean(true);web::json::value v4 = web::json::value::string(U("Hello Again!"));

//...

int32_t av1 = v1.as_integer();double av2 = v2.as_double();bool av3 = v3.as_bool();utility::string_t av4 = v4.as_string();

27

JSON 문자열 파싱

web::json::value obj = web::json::value::object();obj[U("name1")] = web::json::value::string(U("hi there"));obj[U("name2")] = web::json::value::number(77);utility::string_t tmp = obj[U("name1")].as_string();for(web::json::value::const_iterator iter = obj.as_object().begin()

; iter != obj.as_object().end(); ++iter) {std::wcout << iter->first.to_string() << L" : "

<< iter->second.to_string() << std::endl;}

출력값 : "name1" : "hi there""name2" : 77

28

http://www.cafex.com/wp-content/uploads/2012/09/demo_banner.png29

Reference

• C++ REST SDK (codename “Casablanca”)• https://casablanca.codeplex.com/

• REST application programming• http://www.ibm.com/developerworks/aix/library/au-

aem_rest/#resources

• Connecting C++ apps to the cloud via Casablanca• Niklas Gustafsson & Artur Laksberg

• //build/ 3-003

30