Sending a string encoded as Byte array via tcpListener, new string length same like buffer size

1k Views Asked by At

I am in need of creating a small application which sends text chucks. So I created a server using tcpListener. On my client I use tcpClient.

Now my problem:

data = System.Text.Encoding.ASCII.GetBytes("test"); //length of "test" is 4.

now I am sending this byte array to my server application. There I am creating a buffer array with a size of 320000 bytes. (The size really doesn't matter here)

byte[] message = new byte[320000];
bytesRead = clientStream.Read(message, 0, 320000);
ASCIIEncoding encoder = new ASCIIEncoding();
string request = encoder.GetString (message);

And here is my problem now, the resulting request string has a length of 320000. Same size as my byte array. I do understand why it is like that, but what could I do to reduce the size back to it's original? Right now I use a RegEx to remove all chars that would never occur in my strings that I will send... but there must be a proper way of doing so...

Any help will be appreciated :)

Pat.

2

There are 2 best solutions below

1
On BEST ANSWER

Try changing:

string request = encoder.GetString(message);

to

string request = encoder.GetString(message, 0, bytesRead);
1
On

A common practice is to use some identifier that will never appear anywhere else in your string to indicate the end of it.

System.Text.Encoding.ASCII.GetBytes("test+++++++");

Anything will work, and when you find this sequence you (string.indexof("+++++++")) just return a substring of the final result.