套接字连接的字符编码问题

时间:2012-10-16 10:38:00

标签: c# sockets character-encoding tcpclient

我正在向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;
        }
    }

1 个答案:

答案 0 :(得分:3)

如果您确定正在使用的编码是ISO-8859-1那么而不是Encoding.ASCII使用Encoding.GetEncoding("ISO-8859-1")