C# tcp线程中的字符串concat失败

C# tcp线程中的字符串concat失败,c#,string-concatenation,C#,String Concatenation,这是我的密码 while (true) { byte[] btServerReceive = new byte[256]; TcpClient tcpclient = tcp.AcceptTcpClient(); NetworkStream ns = tcpclient.GetStream(); int intReceiveLength = ns.Read(btServerReceive, 0, btServerReceive.Length); stri

这是我的密码

while (true)
{
    byte[] btServerReceive = new byte[256];
    TcpClient tcpclient = tcp.AcceptTcpClient();
    NetworkStream ns = tcpclient.GetStream();
    int intReceiveLength = ns.Read(btServerReceive, 0, btServerReceive.Length);

    string recv = Encoding.GetEncoding("GB2312").GetString(btServerReceive) + "_01";        
    tcpclient.Close();
    MessageBox.Show(recv.ToString());

    // Create a new thread to handle the data associate with recv
    Thread sendUpThread = new Thread(new ParameterizedThreadStart(SendThread));
    sendUpThread.Start(recv);
}
字符串
recv
仅获取
Encoding.GetEncoding(“GB2312”).GetString(btServerReceive)
,无法添加
“\u 01”
”您可以添加“\u 01”。只是您没有注意到,因为字符串显示在一个上下文中,嵌入的空值阻止您看到它

也就是说,您已经将一个256字节的数组传递给
GetString()
方法,其中只有前N个字节被实际修改,其余的仍然具有其初始值0。因此
GetString()
将这些字符解释为“\0”字符,并忠实地包含在返回的字符串中

至少,您必须这样做:

string recv = Encoding.GetEncoding("GB2312")
    .GetString(btServerReceive, 0, intReceiveLength) + "_01";        
也就是说,考虑实际接收的字节数,只解码这么多字节

也就是说,即使这样也不能完全解决你的问题。上述方法可能在大部分时间都有效,但TCP只能返回发送的整个字符串的一部分。由于使用UTF8编码,一些字符由多个字节表示,因此接收到的数据中的最后一个字节当然只能是字符的一部分


要解决这一问题,您需要有一些方法来知道何时读取完字符串(例如,发送以null结尾的字符串、发送长度前缀字符串、固定长度字符串等),或者维护一个
解码器的单个实例,您可以使用该实例对输入的文本进行解码(
Decoder
保留未完全解码数据的内部缓冲区,以便在随后的文本解码调用中,它可以正确处理部分字符)。

非常感谢,我已经学会了。这让我困惑了一个晚上……非常感谢