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?
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.
Since TCP is a stream oriented protocol, there are 3 general ways to know when a message has been completely received:
- the message length is known (either because it’s a fixed length or because something in the protocol tells you how long it is)
- there’s a delimiter at the end of the message that you can check for
- the connection is closed