C++ 生成boosthttp客户端

C++ 生成boosthttp客户端,c++,http,asynchronous,boost,client,C++,Http,Asynchronous,Boost,Client,我是新加入boost library的,所以我的问题可能不是本论坛的第一个问题,但我找不到类似的案例。 目前,我正在尝试实现一个调用RESTAPI的简单HTTP客户机。 我从boost网站上给出的示例中获得了灵感: 对于像我这样的新手来说,这个例子已经足够清楚了,但是我想让客户端能够一个接一个地执行多个请求,因为这个例子是一次性的:客户端向服务器发送GET请求,然后接收响应,然后io_service.run()返回 所以我的问题是,我需要使用boost中的什么来让我的客户机总是等待新的请求发送

我是新加入boost library的,所以我的问题可能不是本论坛的第一个问题,但我找不到类似的案例。 目前,我正在尝试实现一个调用RESTAPI的简单HTTP客户机。 我从boost网站上给出的示例中获得了灵感:

对于像我这样的新手来说,这个例子已经足够清楚了,但是我想让客户端能够一个接一个地执行多个请求,因为这个例子是一次性的:客户端向服务器发送GET请求,然后接收响应,然后io_service.run()返回

所以我的问题是,我需要使用boost中的什么来让我的客户机总是等待新的请求发送

我读了一些关于io_服务::work的文章,但我不确定这是不是正确的方法

有没有人做过和我想做的客户类似的事情? 提前谢谢

致以最崇高的敬意


Anton

我不知道是否必须使用异步版本,因此我建议您尝试使用同步版本,因为遵循执行路径更容易:

/*
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;
}
/*
编译
g++-lpthread-lboost_系统-lboost_线程-ohttp http.cpp
*/
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用std::cout;
使用std::endl;
使用std::vector;
使用std::string;
使用boost::asio::ip::tcp;
使用boost::asio::ip::address;
使用boost::asio::io_服务;
使用boost::asio::buffer;
使用boost::system::error\u代码;
使用boost::system::system\u错误;
int main()
{
尝试
{
无符号整数端口=80;
常量字符串HOST=“216.58.214.238”;
const string HTTP\u REQUEST=“GET/index.html HTTP/1.0\n\n”;
io_服务ios;
tcp::端点ip_端口(地址::从_字符串(主机),端口);
while(true)
{
tcp::套接字客户端(ios);
客户端连接(ip_端口);
常数int BUFLEN=1024;
载体buf(BUFLEN);
send(缓冲区(HTTP_请求,HTTP_请求.size());
错误\代码错误;
int len=client.receive(缓冲区(buf,BUFLEN),0,错误);
库特