服务器端未正确读取消息

Server side not reading message correctly

我正在开发客户端-服务器应用程序,客户端在 Android 中,服务器在 C# 中。在将 C# 用于服务器之前,我使用了 autoIT,它工作正常,除了我必须发送 9 个字符的消息,否则它会得到奇怪的符号。

现在在 C# 中我遇到了同样的问题。我尝试删除所有白色 space 但它总是在邮件开头留下一些内容。

单字消息,例如:

"SendClose" 

服务器读取为

"     SendClose" or " SendClose" if i remove the white spaces

注意前导白色 space。这很有趣,因为当我检查字符串长度时,它说它只有 11 个字符,所以我不知道发生了什么;也许 2 个标签?

这是我的 C# 代码:

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class TcpListenerSample {
  static void Main(string[] args) {
    try {
      // set the TcpListener on port 13000 
      int port = 80;
      IPAddress localAddr = IPAddress.Parse("192.168.1.68");
      TcpListener server = new TcpListener(localAddr, port);

      // Start listening for client requests
      server.Start();


      // Buffer for reading data 
      byte[] bytes = new byte[1024];
      string data;

      //Enter the listening loop 
      while (true) {
        Console.Write("Waiting for a connection... ");

        // Perform a blocking call to accept requests. 
        // You could also user server.AcceptSocket() here.
        TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Connected!");

        // Get a stream object for reading and writing
        NetworkStream stream = client.GetStream();

        int i;

        // Loop to receive all the data sent by the client.
        i = stream.Read(bytes, 0, bytes.Length);

        while (i != 0) {
          // Translate data bytes to a ASCII string.
          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
          Console.WriteLine(String.Format("Received: {0}", data));

          // Process the data sent by the client.
          data = data.ToUpper();

          byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

          // Send back a response.
          stream.Write(msg, 0, msg.Length);
          Console.WriteLine(String.Format("Sent: {0}", data));

          i = stream.Read(bytes, 0, bytes.Length);

        }

        // Shutdown and end connection
        client.Close();
      }
    }
    catch (SocketException e) {
      Console.WriteLine("SocketException: {0}", e);
    }


    Console.WriteLine("Hit enter to continue...");
    Console.Read();
  }

}
      data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
      Console.WriteLine(StripExtended(data));        



        static string StripExtended(string arg)
        {
            StringBuilder buffer = new StringBuilder(arg.Length); //Max length
            foreach(char ch in arg)
            {
                UInt16 num = Convert.ToUInt16(ch);//In .NET, chars are UTF-16
                //The basic characters have the same code points as ASCII, and the extended characters are bigger
                if((num >= 32u) && (num <= 126u)) buffer.Append(ch);
            }
            return buffer.ToString();
        }
    }
}