boost::asio::read function hanging

前端 未结 2 2043
-上瘾入骨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: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 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.

提交回复
热议问题