Russ W.
Russ W.

Reputation: 48

TCP Client reads first message but not the rest

I am trying to send a request to an existing server solution and write out the results. The server is sending a total of 4 messages with my particular request but the number of messsages back can vary depending on the initial query.

I am able to successfully send the query to the server but when it comes to reading the response i can only read one message. The server logs show that 4 were sent back.

Please help.

        IPHostEntry hostEntry = Dns.GetHostEntry(server_textbox.Text);
        IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
        string data = String.Empty;
        testclient = new TcpClient(server_textbox.Text, port);
        testclient.ReceiveBufferSize = 1024;
        testclient.SendBufferSize = 1024;
        NetworkStream netStream = testclient.GetStream();
        Byte[] message_byte = new System.Text.ASCIIEncoding().GetBytes(msg2);
        netStream.Write(message_byte, 0, message_byte.Length);

        Byte[] returnMessage = new byte[1024];
        Int32 totalBytesReceived = 0;
        Int32 bytesReceived = 0;
        try
        {

            while ((bytesReceived = netStream.Read(returnMessage, totalBytesReceived, returnMessage.Length)) > 0)
            {
                totalBytesReceived += bytesReceived;
                data += "\n" + ASCIIEncoding.ASCII.GetString(returnMessage);

                bytesReceived = 0;
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        result_box.Text += data;
        netStream.Close();
        testclient.Close();

    }

Upvotes: 0

Views: 356

Answers (1)

Eric
Eric

Reputation: 19863

My guess is that all your messages are read in the first Read. When the server replies, all the data gets stuck in the windows receive buffer and gets read all at once.

I would recommend using Wireshark, which is more or less mandatory when doing network programming. You'll be able to see the 4 messages coming back from the server as at least 4 different tcp packets.

Upvotes: 2

Related Questions