As you can see I'm receving the data sent, but with those \0 mixed with it. What is causing this? Maybe something with the encoding?
Yes. It's this method:
private static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
It's copying the char
data in binary form - two bytes per character. Don't use this at all - just use Encoding.GetBytes
, having chosen a suitable encoding... I'd suggest Encoding.UTF8
. Use the same encoding on the receiving side. Note that you can't just use Encoding.GetString
as you may receive data which ends half way through a character (if you have any non-ASCII data).
I'd also recommend against using DataAvailable
as an indication of whether a message has finished or not. If you're sending multiple messages on the same stream, you should either length-prefix each message (probably the simplest approach) or use some specific data to indicate the end of the stream.