1

I'm connected to the device I want to query through sockets. I can send commands no problem but when I try to get data back, it will send it back to me in portions so that I never really get the entire message at once. I've resorted to the multiple try-catch sequence to try to get the different portions successively but I just end up with the last chunk. I'm thinking there is a timing issue but not sure, also, the textboxes don't show any text when the code is done, I figure they should at least display some part of what was received. Any suggestions would be much appreciated

            Byte[] Backdata = new byte[64]; //also tried 32, 16, 64           
            MoxaClient = new TcpClient();

            MoxaClient.Connect(NportAddress, NportPort);
            datastream = MoxaClient.GetStream();
            datastream.Write(SCPIcommands, 0, SCPIcommands.Length);

            //Function to wait for all responses         
            try
            {
                datastream.Read(Backdata, 0, Backdata.Length);
                textBox1.Text += Convert.ToChar(Backdata.ToString());
            }
            catch
            {}
            try
            {
                datastream.Read(Backdata, 4, Backdata.Length);
                textBox1.Text += Convert.ToChar(Backdata.ToString());
            }
            catch{}
fifamaniac04
  • 2,343
  • 12
  • 49
  • 72

1 Answers1

1

TCP is stream oriented. You can't rely on "getting the whole message" at once, or in any predictable size of pieces. You have to build a protocol or use a library which lets you identify the beginning and end of your application specific messages. You should read data coming back into a buffer and either prefix the message with a message length or use start/end message delimiters to determine when to process the data in the read buffer.

Search for TCP framing to find some good examples of how to do this. There are several good code examples on StackOverflow including the ones in the answers to this question (although it deals with async sockets).

Sending Messages in a TCP Stream also has some good explanations of how to deal with this.

Community
  • 1
  • 1
Shane Wealti
  • 2,252
  • 3
  • 19
  • 33