Boost.Asio-使用OpenWeatherMap API每隔一定时间获取一次天气(接上一篇)

// 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;
}

运行结果:
在这里插入图片描述

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-15 10:16:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-15 10:16:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-15 10:16:02       87 阅读
  4. Python语言-面向对象

    2024-02-15 10:16:02       96 阅读

热门阅读

  1. MySQL定时备份及清理脚本(一劳永逸)-改良版本

    2024-02-15 10:16:02       55 阅读
  2. JVM指令手册

    2024-02-15 10:16:02       34 阅读
  3. docker命令梳理

    2024-02-15 10:16:02       44 阅读
  4. TCP和UDP面试题提问

    2024-02-15 10:16:02       53 阅读
  5. kafka安装配置(docker)

    2024-02-15 10:16:02       51 阅读
  6. Fabric自动化部署

    2024-02-15 10:16:02       44 阅读
  7. c++游戏服务器开发

    2024-02-15 10:16:02       56 阅读
  8. Linux

    2024-02-15 10:16:02       40 阅读