So I am having trouble reading my string sent through a Tcp stream. I am using this code to send.
byte[] bytes = ASCIIEncoding.ASCII.GetBytes("connect");
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(bytes);
writer.Close();
And this code to read:
public void getConnectionString()
{
NetworkStream ns = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
ns.Read(bytes, 0, bytes.Length);
string info = Encoding.ASCII.GetString(bytes);
MessageBox.Show(info);
}
But all this is returning is System: byte[]
Shouldn’t it return the string? What am I doing wrong?
The problem is that you’re calling
which is in turn calling
TextWriter.Write(object)– which simply callsToString()on thebyte[]. ThatToString()call will returnSystem.Byte[].The point of creating a
StreamWriteris that you can write text:So you don’t need to call
Encoding.GetBytes()yourself at all. However, if you really want to only send ASCII down the socket, you should specify that explicitly when you create theStreamWriter:Of course an alternative is that you don’t bother with a
StreamWriter, and send the bytes directly down the stream. It’s important that you understand the difference though: theStreamAPI deals in binary data; theTextWriterAPI deals in text data. (AndStreamWriterperforms that text to binary conversion for you.)