为什么我的TCP客户端发送中文字符?

时间:2018-01-20 00:51:45

标签: c# .net encoding tcp buffer

所以我正在开发一个非常简单的项目,一个连接到可以接收数据的预制服务器的客户端。 我正在尝试发送一个缓冲区,但是当它恢复缓冲区时它会获得中文图表,即使我正在尝试发送" 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();
        }

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

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

我做了一个类似于你的快速版本,但在"服务器"上进行了解码。作为unicode并获得一些汉字。

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();

答案 2 :(得分:0)

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

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