tags:

views:

17

answers:

2

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?

+3  A: 

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.

Jon Skeet
So essentially, it's the sender's responsibility to close the socket when it's done transmitting data? Ah...I'm doing this in the context of writing a proxy server, so the sender is a web server. Would the web server leave the socket open to handle subsequent requests from the same client?
joelt
@joelt: It depends on the protocol. In HTTP 1.0, each connection was only open for a single request/response pair, so the server closed the socket. For 1.1, the client can request that the connection be kept alive. Then the length of the response is included, and the client should only try to read that much data.
Jon Skeet
A: 

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
Michael Burr