C# TCP 发送带有特殊字符的字符串删除最后一个字符

C# TCP sending string with special char removes last char

发送包含特殊字符的字符串时,发送字符串中的每个特殊字符都会从字符串末尾删除一个字符。 IE: åker -> åke, ååker -> ååk

发送没有特殊字符的字符串 returns 预期的完整字符串。

我的字符串数据包是 writen/read 像这样:

public void Write(string _value)
{
    Write(_value.Length); // Add the length of the string to the packet
   
    //buffer.AddRange(Encoding.ASCII.GetBytes(_value)); // Add the string itself
    buffer.AddRange(Encoding.UTF8.GetBytes(_value)); // Add the string itself
}

public string ReadString(bool _moveReadPos = true)
{
    try
    {
        int _length = ReadInt(); // Get the length of the string
        //string _value = Encoding.ASCII.GetString(readableBuffer, readPos, _length); // Convert the bytes to a string
        string _value = Encoding.UTF8.GetString(readableBuffer, readPos, _length); // Convert the bytes to a string
        Debug.Log("Value: " + _value);
        if (_moveReadPos && _value.Length > 0)
        {
            // If _moveReadPos is true string is not empty
            readPos += _length; // Increase readPos by the length of the string
        }
        return _value; // Return the string
    }
    catch
    {
        throw new Exception("Could not read value of type 'string'!");
    }
}

如您所见,我尝试了 ASCII 和 UTF8,ASCII 特殊字符只是替换为“?”并且字符串没有被切断。

我该怎么做才能解决这个问题? 如果需要更多代码,请告诉我。

您写的是字符串的长度,而不是编码字节的长度。对于多字节字符,这些将有所不同。

public void Write(string _value)
{
    var bytes = Encoding.UTF8.GetBytes(_value);
    Write(bytes.Length); 
    buffer.AddRange(bytes); 
}