boost::asio::read function hanging

前端 未结 2 2039
-上瘾入骨i
-上瘾入骨i 2021-01-26 23:27

If someone could please help me out, I cannot understand how the boost::asio::read function works in boost asio. In boost\'s example they have it declare the buffer size before

相关标签:
2条回答
  • 2021-01-27 00:09

    Usually, you know how much bytes you want to read from the definition of protocol.

    In the opposite case you have to read bytes one by one and observe the error code to stop at the end of connection, file, etc.

    Synchronous methods (for example read) in Boost.Asio are nice for short examples, but in practical use cases you should prefer the asynchronous version async_read, which allows you to cancel or just wait for a next chunk of data without blocking your program.

    0 讨论(0)
  • 2021-01-27 00:31

    I've encountered the same problem. It seems that boost::asio::read is supposed to be hang there until the connected client is closed. Instead, you can use socket.read_some like this:

    using boost::asio::ip::tcp;
    try {
        boost::asio::io_service io_service;
    
        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 9999));
    
        for (;;) {
            tcp::socket socket(io_service);
            acceptor.accept(socket);
    
            std::string message = "server received!\n";
    
            boost::system::error_code error_code;
            boost::asio::streambuf stream_buf;
    
            std::vector<char> buf(1024);
            size_t len = socket.read_some(boost::asio::buffer(buf), error_code);
            std::string received_filename(buf.begin(), buf.end());
            received_filename.resize(len);
            if (error_code) {
                std::cout << "error status: " << error_code.message() << std::endl;
            }
    
            boost::asio::write(socket, boost::asio::buffer(message), error_code);
            if (error_code) {
                std::cout << "error status: " << error_code.message() << std::endl;
            }
            query_database(tree, received_filename, output_folder, db_image_filenames);
        }
    }
    catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    

    This will get the message from the client instantly with a relative short message. Hope this help.

    0 讨论(0)
提交回复
热议问题