2016-08-30 105 views
1

我是新的提升庫,所以我的問題可能不是第一個在這個論壇上,但我找不到類似的情況。 目前我正在嘗試實現一個調用REST API的簡單HTTP客戶端。 我激發了我自己從升壓網站給出的例子:enter link description here提升http客戶端

的例子是一個新手不夠清楚像我,但我想一個是因爲使客戶能夠執行多個請求一個例子是一個鏡頭:客戶端向服務器發送GET請求,而不是接收響應,然後io_service.run()返回。

所以我的問題是我需要從boost中使用,使我的客戶端始終等待新的請求發送。

我讀了一些關於io_service :: work的內容,但我不確定它是否正確。

有沒有人做過類似於我想要創建的客戶端? 在此先感謝!

最佳方面,

安東

回答

1

我不知道,如果異步版本是必須的,所以我建議你給一個嘗試同步版本,因爲它更容易跟隨執行路徑:

/* 
Compile with 
    g++ -lpthread -lboost_system -lboost_thread -ohttp http.cpp 
*/ 

#include <iostream> 
#include <string> 
#include <vector> 
#include <cstdlib> 
#include <boost/asio.hpp> 
#include <boost/asio/ip/tcp.hpp> 
#include <boost/date_time/posix_time/posix_time.hpp> 
#include <boost/thread/thread.hpp> 


using std::cout; 
using std::endl; 
using std::vector; 
using std::string; 
using boost::asio::ip::tcp; 
using boost::asio::ip::address; 
using boost::asio::io_service; 
using boost::asio::buffer; 
using boost::system::error_code; 
using boost::system::system_error; 


int main() 
{ 
    try 
    { 
     unsigned int PORT = 80; 
     const string HOST = "216.58.214.238"; 
     const string HTTP_REQUEST = "GET /index.html HTTP/1.0\n\n"; 

     io_service ios; 
     tcp::endpoint ip_port(address::from_string(HOST), PORT); 

     while (true) 
     { 
      tcp::socket client(ios); 
      client.connect(ip_port); 
      const int BUFLEN = 1024; 
      vector<char> buf(BUFLEN); 
      client.send(buffer(HTTP_REQUEST, HTTP_REQUEST.size())); 
      error_code error; 
      int len = client.receive(buffer(buf, BUFLEN), 0, error); 
      cout << "main(): buf.data()="; 
      cout.write(buf.data(), len); 
      cout << endl; 

      boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); 
     } 
    } 
    catch (system_error& exc) 
    { 
     cout << "main(): exc.what()=" << exc.what() << endl; 
    } 

    return EXIT_SUCCESS; 
} 

由於在每次請求(返回狀態302)之後谷歌(它使用IP地址)關閉連接,因此每次在循環內創建套接字。

在其他一些情況下,HTTP連接不必由服務器關閉,因此可以重新使用套接字。