c++visual-studioboostboost-asio

How can I refactor old boost asio calls


I'm updating an older C++ project that used boost::asio v1.73 to v1.87 using Visual Studio 2019 and C++17 Apparently the library has changed significantly since then. I'm getting this error using boost v1.87:

error C2039: 'query': is not a member of boost::asio::ip::basic_resolver<boost::asio::ip::tcp,boost::asio::any_io_executor>'

Can anyone point me in the right direction to resolve it?

#include <WinSock2.h>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

int main()
{

    try
    {
        boost::asio::io_context io_service;

        tcp::resolver resolver(io_service);
        tcp::resolver::query query("localhost", "5002");
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        tcp::socket socket(io_service);
        boost::asio::connect(socket, endpoint_iterator);

        boost::system::error_code error;
        std::string stmp = "dummy data";
        //boost::asio::write(socket, boost::asio::buffer(stmp), error);
        // following should block until complete or error
        socket.send(boost::asio::buffer(stmp));
        socket.shutdown(tcp::socket::shutdown_both);
        socket.close();
    }
    catch (std::exception& e)
    {
        std::cout << e.what();
    }

}

Solution

  • I'd write

    tcp::resolver resolver(ioc);
    auto          eps = resolver.resolve("localhost", "5002");
    

    With the complete program becoming as below.

    Note that the comment // following should block until complete or error is wrong. send is effectively a synonym for write_some. The docs explicitly state:

    The send operation may not transmit all of the data to the peer. Consider using the write function if you need to ensure that all data is written before the blocking operation completes.

    Full Demo

    #include <boost/asio.hpp>
    #include <iostream>
    
    namespace asio = boost::asio;
    using asio::ip::tcp;
    
    int main() try {
        asio::io_context ioc;
    
        tcp::resolver resolver(ioc);
        auto          eps = resolver.resolve("localhost", "5002");
        
        tcp::socket   socket(ioc);
        connect(socket, eps);
    
        boost::system::error_code error;
        write(socket, asio::buffer("dummy data"s), error);
    
        socket.shutdown(tcp::socket::shutdown_both);
    } catch (std::exception const& e) {
        std::cout << e.what();
    }