|
-
Sep 1st, 2012, 04:42 PM
#1
Thread Starter
New Member
[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.
-
Sep 1st, 2012, 11:05 PM
#2
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.
-
Sep 3rd, 2012, 07:06 AM
#3
Thread Starter
New Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|