【问题标题】:Why is my TCP client sending chineese characters? [duplicate]为什么我的 TCP 客户端发送的是汉字? [复制]
【发布时间】:2018-06-29 07:27:47
【问题描述】:

所以我正在做一个非常简单的项目,一个连接到可以接收数据的预制服务器的客户端。 我正在尝试发送一个缓冲区,但是当它恢复缓冲区时,即使我正在尝试发送“Hello World!”,它也会获得中文字符。

我如何正确编码我的缓冲区,以便当服务器接收到它时,它不会接收到中文字符?

还有..客户端发送完后就卡住了,这是为什么呢?

Visual representation showing what it looks like

const string IP = "127.0.0.1";
        const int port = 12345;
        TcpClient Client = new TcpClient();

        public Form1()
        {
            Client.NoDelay = true;
            InitializeComponent();
        }

        private void SendMessage()
        {
            //Create the message we are going to send.
            string texttoSend = DateTime.Now.ToString();

            //Create a network stream to get all the data that comes and goes through the client.
            NetworkStream nwStream = Client.GetStream();

            //Convert out string message to a byteArray because we will send it as a buffer later.
            byte[] bytesToSend = Encoding.ASCII.GetBytes(texttoSend);

            //Write out to the console what we are sending.
            Console.WriteLine("Sending: " + texttoSend);

            //Use the networkstream to send the byteArray we just declared above, start at the offset of zero, and the size of the packet we are sending is the size of the messages length.
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //Recieve the bytes that are coming from the other end (server) through the client and store them in an array.
            byte[] bytesToRead = new byte[Client.ReceiveBufferSize];

            //read the bytes, starting from the offset 0, and the size is what ever the client has recieved.
            int bytesRead = nwStream.Read(bytesToRead, 0, Client.ReceiveBufferSize);

            //Decode the bytes we just recieved using the Encoding.ASCII.GetString function and give it the correct parameters
            //1. What it should decode
            //2. Starting to decode from what offset
            //3. How much do we want to decode?
            Console.WriteLine("Recieved: " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
            Console.ReadLine();

            //Close the client so we're not leaving it open for people to eavesdrop.
            Client.Close();
        }

        private async Task Connect()
        {

            try
            {
                await Client.ConnectAsync(IP, port);
                btnConnect.BackColor = Color.Green;
                btnConnect.Text = "Connected.";
            }
            catch (Exception e)
            {
                MessageBox.Show("Server refused the connection.", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
                Debug.Print(e.ToString());
            }
        }

        private async void btnConnect_ClickAsync(object sender, EventArgs e)
        {
            await Connect();
        }

        private void btnSendAll_Click(object sender, EventArgs e)
        {
            SendMessage();
        }

【问题讨论】:

  • TCP 不关心语言,更不用说中文了。它只是发送字节。问题出在其他地方
  • 有什么理由让您看起来像是寄给自己的?服务器代码在哪里?
  • 服务器是学校给我们定制的服务器,我无法访问源代码,也无权访问它。
  • @MickyD 我只能访问端口和运行它的 IP,我显然是在我的 PC 上启动它。
  • 请不要破坏您的问题。这样一来,您实际上就是在使本网站志愿者发布的所有帮助、努力和答案都过时了,这对他们来说根本不公平。

标签: c# .net encoding tcp buffer


【解决方案1】:

您确定服务器期待使用 ASCII 编码的请求吗?您看到的问题很可能是服务器和客户端之间的编码不匹配。 NET 默认使用 UTF8。

您还可以使用StreamReaderStreamWriter 来简化一些代码。

private void SendMessage()
{
    //---data to send to the server---
    string textToSend = DateTime.Now.ToString();

    NetworkStream nwStream = Client.GetStream();

    //---send the text---
    Console.WriteLine("Sending : " + textToSend);
    using (StreamWriter nwsWriter = new StreamWriter(nwStream, Encoding.ASCII))
    {
        nwsWriter.Write(textToSend);
    }

    //---read back the text---
    using (StreamReader reader = new StreamReader(nwStream, Encoding.ASCII))
    {
        string responseText = reader.ReadToEnd();
        Debug.Print("Received : " + responseText);
    }

    Client.Close();
}

【讨论】:

    【解决方案2】:

    服务器似乎正在与您的应用程序使用 Unicode 或其他编码。

    我做了一个与你类似的快速版本,但在“服务器”上解码为 un​​icode 并获取一些中文字符。

    http://share.linqpad.net/4bf7ag.linq

    发送:20/01/2018 12:33:59 PM

    收件:〲〯⼱〲㠱ㄠ㨲㌳㔺‹䵐

    //Create the message we are going to send.
    string texttoSend = DateTime.Now.ToString();
    
    //Create a network stream to get all the data that com
    MemoryStream nwStream = new MemoryStream();
    
    //Convert out string message to a byteArray because we
    byte[] bytesToSend = Encoding.ASCII.GetBytes(texttoSen
    
    //Write out to the console what we are sending.
    Console.WriteLine("Sending: " + texttoSend);
    
    //Use the networkstream to send the byteArray we just 
    nwStream.Write(bytesToSend, 0, bytesToSend.Length);
    
    Encoding.Unicode.GetString(nwStream.ToArray()).Dump();
    

    【讨论】:

      【解决方案3】:

      将缓冲区的编码更改为 Unicode!

      byte[] bytesToSend = Encoding.Unicode.GetBytes(texttoSend);
      

      【讨论】:

      • 很好,但你不应该猜测。没有文本,只有编码文本。如果服务器需要文本,则其操作员必须与您沟通它接受哪种单一编码,或者为您提供一种与您沟通您选择使用哪种编码的方式(这显然必须在他们的能力范围内——递归通信要求)。
      猜你喜欢
      • 1970-01-01
      • 2018-09-19
      • 2016-04-25
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多