tags:

views:

174

answers:

1

I'm a little confused about how reading data into a stream works in asio. My main questions are:

  1. What happens if there are multiple asynchronous writes from one computer going on at the same time, and only one asynchronous read on the receiving computer. Over a TCP protocol, is there any chance that the data will get interleaved?
  2. How does the ASIO library know when to call the handler that handles new data in the read stream? Would it call on every received byte? When the client disconnects?
  3. Are there any good (and simple) examples that use a stream, as opposed to a buffer to read from a tcp socket with asio?

thanks.

+2  A: 

What happens if there are multiple asynchronous writes from one computer going on at the same time, and only one asynchronous read on the receiving computer. Over a TCP protocol, is there any chance that the data will get interleaved?

If you call async_write while another asynchronous write operation is in progress, the result is undefined. It's similar to doing two simultaneous write() syscalls on the same socket from two different threads. You could make a big data mess.

How does the ASIO library know when to call the handler that handles new data in the read stream? Would it call on every received byte? When the client disconnects?

If you call async_read, it will call the callback when all the requested amount of data is received. If you call async_read_some, it will call the callback when there is at least one byte, but it may be more. Probably the contents of a single TCP packet sent by the other end.

Are there any good (and simple) examples that use a stream, as opposed to a buffer to read from a tcp socket with asio?

You mean asio::iostream? There are examples in the asio documentation.

Nicolás