Boost logo

Boost Users :

Subject: Re: [Boost-users] Cannot get boost::asio::read_until to properly read a line. [new to boost/asio]
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2015-11-04 17:50:57


On 5/11/2015 07:25, Nick Chambers wrote:
> Hello everyone! I'm writing an IRC framework (still in very rough, early
> stages), and am having trouble reading a single line from the server (in
> this case irc.freenode.net:6667 <http://irc.freenode.net:6667>).
[...]
> void client::irc::send(std::string msg) {
> this->socket.write_some(boost::asio::buffer(msg +
> std::string("\r\n")));
> }

Firstly, be aware that write_some is permitted to write less than the
full amount of data provided, if eg. some internal buffer is nearly
full. If you're not going to check for this, then use the free function
boost::asio::write instead, which handles it for you.

> std::string client::irc::readline() {
> boost::asio::streambuf buffer;
> size_t received = boost::asio::read_until(this->socket, buffer,
> "\r\n");
> std::istream is(&buffer);
> std::string line;
> std::getline(is, line);
> return std::string(std::begin(line), std::end(line)-1);
> }

Secondly, note that read_until may (and usually does) read data beyond
the delimiter into the buffer. It is therefore essential to preserve
this buffer between calls (ie. don't make it a local variable), and to
properly mark the bytes that you are extracting from it as consumed so
that you don't keep getting the same line again.

This also means that you shouldn't mix calls to read_until with other
read calls on the same socket, at least not without taking the buffer's
existing contents into account.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net