Re: [Boost-users] Boost.Asio -- combining sync read with async read (Igor R)
It's ok to use both sync. and async. calls, but you should not call boost::asio::async_read_until() and/or boost::asio::async_read() until previous read is complete (for the same socket/buffer). Besides, pay attention that reading "until" might read more data than you expect.
Thanks Igor, I'm a bit confused here though.. how do I know if the previous read is complete? I figured when async_read_until() calls the handler, the read was complete and everything read was sitting in the buffer? Do you mean to say that if the client receives two lines, then async_read_until() will read both lines but then put only the first line in the buffer? Then I can't call async_read_until() again because there is still another pending call to the handler that will process the second line? So how do I know at the end of the handler whether or not to call async_read_until() ? thanks! -Sameer
how do I know if the previous read is complete? I figured when async_read_until() calls the handler, the read was complete and everything read was sitting in the buffer?
Do you mean to say that if the client receives two lines, then async_read_until() will read both lines but then put only the first line in
Then I can't call async_read_until() again because there is still another
Correct. But do not call another asio::async_read_until() before the first one's handler is invoked (for the same socket). the buffer? No, it will read anything available in the socket and put it in the buffer. It can be 1 line, 2 lines or 3.25 lines. What I mean is that you have to be aware of the fact that the buffer might contain more data than you "requested" from read_until. pending call to the handler that will process the second line? So how do I know at the end of the handler whether or not to call async_read_until() ? Every time you get the read hanlder called, you have to call async_read_XXX again - until your application decides that it doesn't want data from the server anymore. But imagine the following scenario (though I don't know if it's relevant to your application): you expect 3 lines from the server, and want to process them line by line. //... asio::async_read_until(socket_, buffer_, "\r\n", ...); //... void handle(...) { process(buffer_); asio::async_read_until(socket_, buffer_, "\r\n", ...); } If the server may send 3 lines at once, and process() function assumes that the buffer contains 1 line, it's a bug: the 2 latter lines in the buffer_ will never be processed, and the second async_read_until() will never complete, because the server already sent all it wanted.
participants (2)
-
Igor R
-
Sameer Parekh