Results 1 to 3 of 3

Thread: [RESOLVED] TCP client issue

  1. #1
    New Member
    Join Date
    Sep 12
    Posts
    2

    Resolved [RESOLVED] TCP client issue

    Hello. I am using a TCP client to send and receive data, but for some reason the data it receives has a bunch of white spaces at the end of each message.

    Code:
        System.Text.StringBuilder income_message_client = new System.Text.StringBuilder();
    
        void Manage_Connection_Client()
        {
            do
            {
                int read;
                do
                {
                    byte[] bytes = new byte[client.ReceiveBufferSize];
                    read = client.GetStream().Read(bytes, 0, bytes.Length);
                    income_message_client.Append(System.Text.Encoding.UTF8.GetString(bytes));
                }
                while (read == 0);
                //do things based on data received
            }
            while (true);
        }
    The data I receive is: "Blablablabla123 (space) (space) (space) (space) (space) (space) (space) (space) (space)", while the data I send truly is "Blablablabla123"
    (space) = " "
    Last edited by Krotcha87; Sep 1st, 2012 at 04:49 PM.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,793

    Re: TCP client issue

    You are creating a buffer of a particular size and then writing the data received into that buffer, but the data received is not necessarily enough to fill that buffer. You then convert the entire buffer to a String, so you're also converting the portion of the buffer that wasn't filled. The Read method returns a number that represents the number of Bytes read. The whole point of that value is so that you know how many Bytes of the buffer to use. You have used a variable named 'read' to store that value. When you convert the data received to a String you need to use that value to specify how much of the buffer to convert.

  3. #3
    New Member
    Join Date
    Sep 12
    Posts
    2

    Re: TCP client issue

    Thanks a lot, jmcilhinney.
    You were right, it turns out all I had to do was change this line:
    Code:
    income_message_client.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, read));
    Thanks very much again!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •