【发布时间】: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