简体   繁体   中英

boost asio socket async read methods block until a newline is received

I am (in effect) writing a telnet-like app. (It's far more complicated than that.) I need to receive inbound IP connections and transfer data. I'm using boost::asio to do the socket work.

Everything is fine, except I haven't been able to convince asio to call my handler the moment data is available. To test, I telnet to my host/port (that is working), type something, and hit newline. My debug output appears. That's great.

If I don't hit newline, my app is quiet. I might as well just be calling "readline".

I have tried a variety of things. I tried doing async_read_until, passing a method that returns a pair when there is any data. It doesn't get called until a newline.

I tried using async_read with a 1-byte buffer. It gets called n times as appropriate, but only once I hit newline on the terminal.

And for that matter, telnet is echoing the characters as I type, which also seems like a hint.

Here's the code for using async_read_until:

boost::asio::async_read_until(socket, receiveBuffer, haveData,
        boost::bind(&TCPConnection::dataReceived,
              shared_from_this(),
              boost::asio::placeholders::error));

std::pair<TCPConnection::Iterator, bool>
haveData(TCPConnection::Iterator begin, TCPConnection::Iterator end)
{
    if (begin != end) {
        return std::make_pair(end, true);
    }
    // no data.
    return std::make_pair(begin, false);
}

Here's the code for using a 1-byte buffer:

char * buffer = new char(1);

auto hPtr = boost::bind(&TCPConnection::handler,
        shared_from_this(), boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred);
boost::asio::async_read(socket, boost::asio::buffer(buffer, 1), hPtr);

My socket definition:

boost::asio::ip::tcp::socket socket(io_service);

I presume (somehow) I need to get the socket into a different mode than it's in. I don't have a clue how.

In more fairness, I hate the 1-byte-buffer thing. I'd rather give it a proper size buffer but have it wait until there's any data, but then just give me what it's got. But if I have to read them 1 byte at a time, I can live with that.

Okay, consider this answered. It wasn't my program. It was telnet, which by default is in line mode. See Daniel's question and my responses in the comments to the original post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM