0

I'm troubleshooting an application that uses NetworkStream to send data and receive data. I have a couple questions related to NetworkStream.DataAvailable and NetworkStream.Read

Here is code:

    try
    {
     if(DataAvailable)
     {
      numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
      myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
     }

   catch
     {}
   }

The server sends back data in 5 packets every time.

Questions:

Does read method above receive all the packets or only random packets(1-5)?

Does the NetworkStream.DataAvailable reset to False after the data is read? and set to True again if a new packet is arrived(Assume answer for question 1 is random packets)?

Thanks!!!

Michael
  • 21
  • 1
  • 1
  • 4
  • You are reading TCP datagrams. A TCP datagram has a maximum of ~1500 bytes. The Network Card on the PC, routers, and server split and recombine datagrams so you may get pieces of your message when you read. – jdweng Jan 26 '18 at 18:15
  • On the application layer TCP has no notion of packets. Your data is lumped together in a continuous stream of bytes (hence why you use a Network _**Stream**_) and one call to `Read()` reads all data it has received so far, which could both be more or less than what you sent in one of your `Send()` calls. Here on Stack Overflow we like to express this by saying: _"One `Send` usually does not equal one `Read`"_. – Visual Vincent Jan 29 '18 at 16:15
  • In order to have any notion of where your data begins and ends (and whether you've received enough) you've got to implement something called _message framing_. In two of my previous answers you can find a [description of how to implement it](https://stackoverflow.com/a/37352525/3740093) and also an [example implementation](https://stackoverflow.com/a/35240061/3740093) (the latter is in VB.NET, but there is a C# source linked in the answer). – Visual Vincent Jan 29 '18 at 16:22
  • As for your second question, yes: `DataAvailable` is reset to `false` when you've read all data (_**not**_ packets, since you are just reading a stream of bytes) that your computer has received **so far**. When it receives new data `DataAvailable` is set to `true` again. – Visual Vincent Jan 29 '18 at 16:29

0 Answers0