【问题标题】:C# TCP sending string with special char removes last charC# TCP 发送带有特殊字符的字符串删除最后一个字符
【发布时间】:2020-11-14 01:50:13
【问题描述】:

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

发送没有特殊字符的字符串会按预期返回完整的字符串。

我的字符串数据包是这样写/读的:

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 特殊字符只是替换为 '?'并且字符串没有被切断。

我可以做些什么来解决这个问题? 如果需要更多代码,请告诉我。

【问题讨论】:

    标签: c# string encoding tcp network-programming


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2019-11-09
      • 2016-10-11
      • 1970-01-01
      • 2011-12-15
      相关资源
      最近更新 更多