How do I get an entire response from a socket?

We are using the .net class for some ftp functionality.

After sending a command on an open socket we call the socket.receive (buffer).  This puts a certain number of bytes into the buffer and returns the number of bytes.

The problem is that sometimes the operation returns 0 but we have not received the entire response.   The next call to the receive method will then return the remaining message from this command PLUS the response generated by the subsequent command.
We suspect this happens due to network latency and varying ftp server loads etc.

My question is how can we reliably know when we have read back the entire outstanding response from the socket?
LVL 12
Who is Participating?
Paul_Harris_FusionAuthor Commented:
Found it

Problem was not with the socket but with my lack of knowledge of the FTP protocol.    
FTP returns a Code and an optional comment in response to a command.   The separator between the code and the command is either a space or a hyphen.  The space indicates that the entire response has now been received whereas the hyphen indicates more is to come.
When using the FTP protocol, you receive messages (Acknowledgments) that signal whether the server has finished uploading the file or not. You have to handle some sort of protocol.
If you know how much to read, insert that as buffer size even if your buffer is bigger to only read the remaining bytes.
Paul_Harris_FusionAuthor Commented:
Juan - the problem is in knowing that I have received the entire message back from the server via the socket.

Werrock - I am doing this already.

The problem is that I submit a command and then call the Receive method on the socket with a buffer of e.g. 512 bytes and the method returns say 200 bytes.    Receiving less than the buffer size back normally indicates that all data has been received.   However,  when we submit the next command and issue another Receive,  the first part of the response is the remainder from the previous command.   The problem seems to be related to server speed.   Our only workaround to date is putting in thread sleeps to allow the server time to send its response but this obviously slows the component down.

We have tried using the Available property on the .Net socket but this suffers from the same problem - if the server is slow to respond, the socket does not know that a response is coming.

I was hoping that there was some reliable End-of-message marker that we could look for.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.