Tuesday, April 5, 2011

How to use string for TcpClient in C# instead of byte?

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.

From stackoverflow
  • Create a StreamWriter on top of outputClient.GetStream:

    StreamWriter writer = new StreamWriter(outputClient.GetStream(),
                                           Encoding.ASCII);
    writer.Write(message);
    
    Andrew Rollings : Would he need to encode the length of the string as part of the stream too, or is that handled automagically?
    Jon Skeet : 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.

0 comments:

Post a Comment