Boost.asio 超时处理

时间:2022-09-09 14:16:50

1.5s后关闭socket

demo

// overtimeClient.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#define BOOST_ASIO_DISABLE_STD_CHRONO
#include <iostream>
#include <boost/asio.hpp>
#include <boost/chrono.hpp>
#include <boost/asio/steady_timer.hpp>
using namespace boost::asio;

int main()
{
    io_service io;
    ip::tcp::socket sock(io);
    ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 6688);

    sock.async_connect(ep, [](const boost::system::error_code&) {});    //异步连接

    steady_timer t(io);
    t.expires_from_now(boost::chrono::milliseconds(5000));    //开始计时

    t.async_wait(    //异步等待超时
        [&](const boost::system::error_code&) {    //使用lambda表达式
        std::cout << "time expired." << std::endl;
        sock.close();    //关闭socket
    }
    );

    std::vector<char> str(sock.available() + 1, 0);
    boost::system::error_code ec;
    for (;;)
    {
        sock.read_some(buffer(str), ec);
        if (ec)
        {
            break;
        }
        std::cout << &str[0];
    }

    std::cout << "syschronous client." << std::endl;
    std::cout << "syschronous client." << std::endl;
    std::cout << "syschronous client." << std::endl;
    std::cout << "syschronous client." << std::endl;
    std::cout << "syschronous client." << std::endl;

    io.run();    //进入异步事件循环
    getchar();
    std::cout << "Hello World!\n"; 
}