c++ – boost asio connect() succeeds but read() fails with `Error (end of file)`

EOF is signaled when the peer shutdown the sending side. It’s not an error, unless of course you don’t expect it to happen.

Just deal with partial success if your application expects it:

Live On Coliru

#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;
using asio::ip::tcp;

struct Conn {
    Conn() = default;

    using error_code = boost::system::error_code;

    void start() {
        error_code ec;
        socket_.connect(tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 1234),
                        ec);
        if (ec) {
            // Log error
        } else {
            do_read();
        }
    }

    void do_read() {
        std::vector<char> buffer(20);

        error_code   ec;
        const size_t n = boost::asio::read(socket_, boost::asio::buffer(buffer), ec);
        std::cout << "Received " << n << " bytes (" << ec.message() << ")" << std::endl;

        if (!ec.failed() || (n && ec == asio::error::eof)) { // success or partial success
            //
        }
    }

    asio::io_context ioc;
    tcp::socket      socket_{ioc};
};

int main() {
    Conn c;
    c.start();
}

Build

g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp

Test

(printf 'short message' | nc -w 1 -l -p 1234& sleep .5; ./a.out; wait)
Received 13 bytes (End of file)
(printf 'longer message over 20 chars' | nc -w 1 -l -p 1234& sleep .5; ./a.out; wait)
Received 20 bytes (Success)

Read more here: Source link