Reputation: 28
I'm using a network stream to transmit data from a text box in windows forms, when this data is read I write it out to the console, while the transmitted data outputs fine it seems to generate a strange gap that I haven't been able to identify as a new line or as a lot of spaces.
I've tried using the Replace function to replace spaces ' ' and new lines '\n' with null characters but this seems to have not fixed the problem and there is still an abnormal gap between the read data and whatever comes after it.
The output should say: John Doe joined
But instead says:
John Doe
joined
TcpClient clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
clientSocket.GetStream().Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(bytesFrom);
Console.WriteLine($"{dataFromClient} joined");
Upvotes: 0
Views: 170
Reputation: 131706
Your code is trying to decode the entire bytesFrom
array, whether it contains data or not. Stream.Read
doesn't overwrite the entire buffer, it overwrites only the bytes it needs and returns the number of bytes.
This means that the first time you try to decode the buffer you'll be trying to decode the 0
s it contains as well. The second time you may end up decoding mixed old and new data.
You should change your code to :
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
using(var stream=clientSocket.GetStream())
{
var read=stream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
var text = Encoding.ASCII.GetString(bytesFrom,0,read);
Console.WriteLine("Actual Text: {0}",text);
}
Another problem is that Encoding.ASCII
is the 7-bit US-ASCII codepage. Any character that isn't contained in that codepage will be lost and replaced by ?
. .NET strings are Unicode (UTF16). Use the UTF8 encoding at least, both on the server and client to avoid losing data
Upvotes: 1