NetworkStream.Read long messages problem

Hi,

I am quite novice to networks and tcp/ip so it might be a silly one.

My problem is that whenever I send long messages over WAN from a client and read them using NetworkStream.Read in the server, I'm not reading a complete message but only part of it (The buffer is bigger than the byte array actually read) which causes the messsage parser to fail.

Am I responssibe for checking that the whole message arrived by using NetworkStream.Read over and over until the whole message was received? Doesn't TcpClient know whether the message has arrived successfully? What are the common patterns for handling similar situations? Code snippets would be appritiated!
comp2000Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

philowareCommented:
//***You can't receive all the data at once with TCP/IP
//***Try this function which will  read data exactly the given size in a loop
private void ReadData(Socket socket, ref byte []buffer, int dataSize)
{
  int size,index = 0;
 
  if(buffer == null || buffer.Length < dataSize)
   buffer = new byte[dataSize];
     
  while(dataSize > 0)
  {              
     size = socket.Receive(buffer,index,dataSize,SocketFlags.None);
     if(size == 0)
          throw(new Exception("Connection closed"));
     dataSize -= size;
     index += size;                        
   }
}
comp2000Author Commented:

Thanks, it does seem like a good solution and I'll give it a try but how exactly do I know the data size? Do I have to add my own header to the data? Is there a common pratice for adding a header to your data?

Also, how do I mark the end of the message and how do I recover from a corrupted message?
philowareCommented:
You can define a heder and send the data size before sending data. Please read my answer to the below question.
http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21477662.html

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.