ASIO async I/O with iostream?
Good afternoon all, I'm interested in writing a program using asio. I'm new to both boost and asio. Is it possible to use async I/O with streams? A stream is a good method for what I'm interested in doing but I don't see how to make it work. What I've got so far: A class using event driven async I/O. The class parses the data into variable arbitrary sized messages. I read from the tcp socket into a buffer, then create a stream from the buffer, then deserialize the data from the stream. unsigned char buffer[1024]; // connect receive event socket->async_read_some( boost::asio::buffer(buffer), boost::bind( &TcpConnection::receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) ); I'd like to be able to skip the buffer and just read directly to the stream with an event to notify me of the arrival of data. Thanks! -- Cause united breaks guitars http://www.youtube.com/watch?v=5YGc4zOqozo
I'd like to be able to skip the buffer and just read directly to the stream with an event to notify me of the arrival of data.
You can use asio::streambuf. It inherits std::streambuf, and you can use it with istream and ostream, just as you do with standard streambufs. But note that any buffer must outlive the async.operation.
On Wed, Dec 9, 2009 at 1:18 PM, Igor R
I'd like to be able to skip the buffer and just read directly to the stream with an event to notify me of the arrival of data.
You can use asio::streambuf. It inherits std::streambuf, and you can use it with istream and ostream, just as you do with standard streambufs. But note that any buffer must outlive the async.operation.
I found an example (below) but it seems to be pretty much the same as my current code to write to a character array and copy the buffer into the stream. It also looks like it might choke if the read was larger than 512 bytes. Thanks for the suggestion anyway though. boost::asio::streambuf b; // reserve 512 bytes in output sequence boost::asio::streambuf::const_buffers_type bufs = b.prepare(512); size_t n = sock.receive(bufs); // received data is "committed" from output sequence to input sequence b.commit(n);
I found an example (below) but it seems to be pretty much the same as my current code to write to a character array and copy the buffer into the stream.
The advantage of asio::streambuf is that it has input and output areas, so you can perform i/o in a convenient manner. Look into examples/reference/tutorial for details.
It also looks like it might choke if the read was larger than 512 bytes.
It will not "choke", the completion handler will be called when it's full.
participants (2)
-
Igor R
-
Jay Sprenkle