joelt
joelt

Reputation: 2680

When does EndReceive return zero bytes

I'm trying to get a better handle on using sockets asynchronously. According to this article, http://msdn.microsoft.com/en-us/library/bew39x2a(v=VS.85).aspx, I ought to be able to check the number of bytes returned by EndReceive, and if it's zero, I know I have all the data, and if it's non-zero, there may or may not be more data coming. This makes sense, but when I call BeginReceive for the last time, it's often several minutes before the callback function gets called...I assume something has to time out, but changing the Socket.ReceiveTimeout property doesn't seem to have an effect.

Is this really the right pattern to use to determine when I've received all the data? Especially when I don't know the format of the message I'm receiving?

Upvotes: 1

Views: 2680

Answers (2)

Michael Burr
Michael Burr

Reputation: 340218

Since TCP is a stream oriented protocol, there are 3 general ways to know when a message has been completely received:

  1. the message length is known (either because it's a fixed length or because something in the protocol tells you how long it is)
  2. there's a delimiter at the end of the message that you can check for
  3. the connection is closed

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500585

It depends on what you mean by "all the data". Has the other end closed the socket? If not, you haven't really read all the data, because the server could send more at any minute.

If the other end has closed the socket, then the callback should occur pretty quickly.

Upvotes: 3

Related Questions