【问题标题】:boost asio connect() succeeds but read() fails with `Error (end of file)`boost asio connect() 成功但 read() 失败并出现“错误(文件结尾)”
【发布时间】:2023-02-21 22:28:21
【问题描述】:

我有以下代码使用 Boost Asio 连接和读取 TCP 套接字。

connect() 成功,但在调用 read() 时出现“错误(文件结尾)”。

代码有问题,还是网络设置有问题?

#include <boost/asio.hpp>

struct Conn
{
   Conn(){}

   void start()
   {
      boost::system::error_code ec;

      // Not the real IP and port
      socket_.connect( tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), 1234 ), ec);
      if(ec)
      { 
          // Log error
      }
      else
      {
          listen();
      }
   }

   void listen()
   {
       std::vector<char> buffer;
       const int bytes_to_read = 20;
       buffer.resize(bytes_to_read);

       boost::system::error_code ec;
       const size_t n = boost::asio::read(socket_, boost::asio::buffer(buffer), ec);
       if(ec)
       { 
           // Fails with 'Error (end of file)'
       }
   }

   tcp::socket socket_;
};

【问题讨论】:

    标签: c++ boost tcp network-programming boost-asio


    【解决方案1】:

    当对等方关闭发送方时,会发出 EOF 信号。这不是错误,除非您当然不希望它发生。

    如果您的应用程序期望它,只需处理部分成功:

    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();
    }
    

    建造

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

    测试

    (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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 2014-05-04
      • 2021-12-02
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多