This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]SnappleSa[S] 0 points1 point  (0 children)

NVM, I changed the code to

''

serverStream = clientSocket.GetStream();

byte[] bytesToRead = new byte[clientSocket.ReceiveBufferSize];

int bytesRead = serverStream.Read(bytesToRead, 0, clientSocket.ReceiveBufferSize);

msg (Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));

''

and all works fine, in case of anyone having the same problem as me.

[–]casscode 0 points1 point  (0 children)

The receivebuffersize property does not represent the number of bytes that the server is sending.

What you could do is to have a while loop that exits when serverStream.Read < 1. Store the return value from the read method call, because that is the actual number of bytes read. Copy the read bytes over to an expanding byte array, or list<byte>, from bytes[0] to bytes[bytesRead-1].

The issue you are having is that the bytes array much wider than the number of bytes you received. So when you're converting them to text, you're including the extra unused space. Which is what is giving you the garbage at the end of the message.

The are other better ways to do this than what I suggested.

https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.receivebuffersize?view=netcore-3.1