1

In C# I try to send a string through TcpClient as such:

byte[] outputOutStream = new byte[1024];
ASCIIEncoding outputAsciiEncoder
string message //This is the message I want to send
TcpClient outputClient = TcpClient(ip, port); 
Stream outputDataStreamWriter   

outputDataStreamWriter = outputClient.GetStream();
outputOutStream = outputAsciiEncoder.GetBytes(message);
outputDataStreamWriter.Write(outputOutStream, 0, outputOutStream.Length);

I must to convert message from string to bytes, is there a way I can send it directly as string?

I know this is possible in Java.

1 Answer 1

10

Create a StreamWriter on top of outputClient.GetStream:

StreamWriter writer = new StreamWriter(outputClient.GetStream(),
                                       Encoding.ASCII);
writer.Write(message);

(You may want a using statement to close the writer automatically, and you should also carefully consider which encoding you want to use. Are you sure you want to limit yourself to ASCII? If you control both sides of the connection so can pick an arbitrary encoding, then UTF-8 is usually a good bet.)

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

4 Comments

Would he need to encode the length of the string as part of the stream too, or is that handled automagically?
The stream of data doesn't contain the length of the string. If he wants to do that, BinaryWriter would probably be a better bet. It will depend on the protocol, basically.
Encoding.UTF8 is likely a safer bet unless you know the other end is explicitly ASCII, double so if you're working on HTTP.
@JosephLennox: I only used ASCII on the grounds that the OP did too. Guessing at any encoding is a bad idea; you should know exactly which encoding both sides are meant to use. I'll add a suggestion for UTF-8 in the answer though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.