0

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?

1 Answer 1

2

The problem is that you're calling

writer.Write(bytes); 

which is in turn calling TextWriter.Write(object) - which simply calls ToString() on the byte[]. That ToString() call will return System.Byte[].

The point of creating a StreamWriter is that you can write text:

writer.Write("connect"); 

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 the StreamWriter:

StreamWriter writer = new StreamWriter(stream, Encoding.ASCII); 

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: the Stream API deals in binary data; the TextWriter API deals in text data. (And StreamWriter performs that text to binary conversion for you.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.