2016-08-30 45 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连接不必由服务器关闭,因此可以重新使用套接字。