Is BeginRead guaranteed to read any incoming bytes that arrive after a call to it?
Let's say that after BeginRead is called, there is other code that will ultimately trigger the arrival of the bytes I want to read. Is t开发者_C百科he following scenario ever possible:
(1) Call to BeginRead is made, passing in 'buf' and returns
(2) Other code executes that is guaranteed to be subsequent to (1) and results in bytes being sent to a port
(3) Bytes arrive destined for the port but are not read into 'buf' due to some timing issue
I would not expect it to be possible but am looking for confirmation from someone experienced. If this is somehow possible, then what would be an alternative to get the guarantee I'm looking for?
BeginRead
will finish when some data is available - but how much data isn't guaranteed. The most obvious example is if the buffer has already been filled before your "extra" data is sent to the port... but equally the buffer doesn't have to be filled - for example, in a network stream, BeginRead
might return when a single packet has been read, even if there are more on the way.
You're likely to want to call BeginRead
repeatedly until you've either read all of the data in the stream (i.e. the other end has closed the connection) or you've read as much as you were trying to (e.g. the whole of a length-prefixed message).
If you want to do proper network communication you WILL have to do application level framing.
Really though, the easiest thing to do would be to use a messaging library that takes care of all of this for you. Take a look at zeromq, it's really great and there's a .NET binding for it.
The bytes are probably there but they just might not be where you are looking for them. It is hard to say without seeing the code. I would suggest using WireShark to watch to make sure the data you think is being sent really is.
精彩评论