C # - TcpClient - End of stream detection?

I'm trying to connect an old network camera to my computer, and I'm stuck in a very fundamental problem - I find the end of the stream.

I use TcpClient to communicate with the camera, and I really see that it sends these commands, there is no problem.

  List<int> incoming = new List<int>(); TcpClient clientSocket = new TcpClient(); clientSocket.Connect(txtHost.Text, Int32.Parse(txtPort.Text)); NetworkStream serverStream = clientSocket.GetStream(); serverStream.Flush(); byte[] command = System.Text.Encoding.ASCII.GetBytes("i640*480M"); serverStream.Write(command, 0, command.Length); 

Reading the answer is where the problem begins. Initially, I thought something was simple, like the following bit of code: [/ p>

  while (serverStream.DataAvailable) { incoming.Add(serverStream.ReadByte()); } 

But this is not so, so this time I had a different version using ReadByte (). The description indicates:

Reads a byte from the stream and advances the position within the stream by one byte or returns -1 if at the end of the stream.

so I thought I could implement something like:

  Boolean run = true; int rec; while (run) { rec = serverStream.ReadByte(); if (rec == -1) { run = false; //b = (byte)'X'; } else { incoming.Add(rec); } } 

No, it still doesn't work. I really see the data coming in after a certain point (which is not always the same, otherwise I could just read that many bytes every time). I am starting to get 0 as the value for the rest of the elements, and it doesn't stop until I stop the execution manually. Here's what it looks like: data

So my question is: did I miss something fundamental here? How can I determine the end of a stream?

Many thanks,

N.

+8
c # sockets tcpclient networkstream
source share
2 answers

What you are missing is the way you think about TCP data flow. This is an open connection, like an open telephone line - someone on the other end may or may not speak ( DataAvailable ), and just because they paused to take a breath ( DataAvailable==false ), it doesn’t mean re really DONE with their current expression. After a moment, they can start talking again ( DataAvailable==true )

You must have specific rules for the ABOVE TCP communication protocol, which is actually only a transport layer. So, for example, the camera may send you a special sequence of characters when the current image transfer is completed, and therefore you need to examine each sent character and determine whether this sequence has been sent to you, and then act accordingly.

+14
source share

Well, you cannot tell EOS exactly about network communication (unless the other side disconnects the connection), usually the protocol itself contains something to signal that the message is complete (sometimes, for example, a new line). That way, you read the stream and feed the buffer, and you retrieve the full message using these strategies.

+2
source share

All Articles