我正在将数据发送到Socket和连接并检索一些数据。我正在检索的数据(这是一个XML文档)包含诸如ä,ü,ö,...的变音符号,但这些符号未正确编码,我只能得到?或)))@符号而不是变音符号。
有什么不正确的方式我如何检索数据?数据以ISO-8859-1编码发送回去。
我的代码:
public bool GetData()
{
try
{
TcpClient tcpClient = new TcpClient("THEIP", 5004);
NetworkStream ns = tcpClient.GetStream();
if (ns.CanWrite)
{
string text = this.xmlRequest;
byte[] sendBytes = Encoding.ASCII.GetBytes(text);
string sendData = Encoding.ASCII.GetString(sendBytes);
ns.Write(sendBytes, 0, sendBytes.Length);
}
System.Threading.Thread.Sleep(2000);
int i = 0;
if (ns.CanRead)
{
do
{
byte[] recvBytes = new byte[tcpClient.ReceiveBufferSize];
i = i + ns.Read(recvBytes, 0, tcpClient.ReceiveBufferSize);
string returnData = Encoding.ASCII.GetString(recvBytes);
returnData = returnData.Substring(0, i);
this.xmlResponse = returnData;
} while (ns.DataAvailable);
}
// got full data...
bool status = this.ProcessXMLData();
ns.Close();
if (status)
{
return true;
}
else
{
return false;
}
}
catch (SocketException se)
{
this.errorFlag = true;
this.errorMessage = se.Message;
return false;
}
}
最佳答案
如果您确定正在使用的编码是ISO-8859-1,则使用Encoding.ASCII
代替Encoding.GetEncoding("ISO-8859-1")
关于c# - 套接字连接的字符编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12912833/