// Asio1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <algorithm>
#include <functional>
using boost::asio::ip::tcp;
void getWeather(const boost::system::error_code& error,
boost::asio::io_context *io, tcp::resolver::results_type* endpoints_,
boost::asio::steady_timer* t, int* count)
{
if (!error)
{
if (*count > 5)
{
cout << "请求次数达到上线,断开连接" << std::endl;
return;
}
// 发送HTTP请求获取天气信息
// 解析返回的JSON数据并提取所需的天气信息
// 输出天气信息
std::cout<<"第" << *count << "发送请求" << std::endl;
++(*count);
tcp::socket socket_(*io);
boost::asio::connect(socket_, *endpoints_);
// http request
std::string request = "GET /data/2.5/weather?q=BeiJing&appid=c7c9b47。。。你自己的密钥 HTTP/1.1\r\n"
"Host: api.openweathermap.org\r\n"
"Connection: close\r\n\r\n";
boost::asio::write(socket_, boost::asio::buffer(request));
//response
boost::asio::streambuf rspStreamBuf;
boost::asio::read_until(socket_, rspStreamBuf, "\r\n");
std::cout << &rspStreamBuf << std::endl;
t->expires_at(t->expiry() + boost::asio::chrono::seconds(5));
t->async_wait(std::bind(getWeather, boost::asio::placeholders::error,io,endpoints_, t, count));
}
else
{
std::cout << "Error: " << error.message() << std::endl;
}
}
int main()
{
boost::asio::io_context io;
// host port
tcp::resolver tcpResolver(io);
tcp::resolver::results_type endPoints = tcpResolver.resolve("api.openweathermap.org", "http");
boost::asio::steady_timer timer_(io, boost::asio::chrono::seconds(5));
int count = 1;
// 设置定时器回调函数
timer_.async_wait(std::bind(getWeather, boost::asio::placeholders::error, &io, &endPoints, &timer_, &count));
// 启动事件循环
io.run();
return 0;
}
运行结果: