【问题标题】:Character encoding issues with Socket Connection套接字连接的字符编码问题
【发布时间】:2012-10-16 22:27:09
【问题描述】:

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

【问题讨论】:

    标签: c# sockets character-encoding tcpclient


    【解决方案1】:

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

    【讨论】:

    • 会有什么不同吗? Ascii 编码通常与 ISO-8859-1 互换使用
    • Encoding.ASCII 使用 7 位和 Encoding.GetEncoding("iso-8859-1") 使用 8 位
    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 2017-04-15
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多