In C# I try to send a string through TcpClient as such:
在C#中我尝试通过TcpClient发送一个字符串:
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.
我知道这在Java中是可行的。
1 个解决方案
#1
Create a StreamWriter
on top of outputClient.GetStream:
在outputClient.GetStream之上创建一个StreamWriter:
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.)
(您可能需要一个using语句来自动关闭编写器,您还应该仔细考虑要使用的编码。您确定要将自己限制为ASCII吗?如果您控制连接的两端,那么可以随意选择编码,然后UTF-8通常是一个不错的选择。)
#1
Create a StreamWriter
on top of outputClient.GetStream:
在outputClient.GetStream之上创建一个StreamWriter:
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.)
(您可能需要一个using语句来自动关闭编写器,您还应该仔细考虑要使用的编码。您确定要将自己限制为ASCII吗?如果您控制连接的两端,那么可以随意选择编码,然后UTF-8通常是一个不错的选择。)