在 stackoverflow 上找不到这个,我确实有一个我几个月前写的例子,但现在也找不到了。

基本上,我将 byte[] 从客户端发送到服务器,在服务器窗口中显示它,然后计划对其中的数据采取行动。然而,我收到的数据并不是每次都被清理,例如:

我发送“ABCDEF”
服务器显示“ABCDEF”
我发送“GHI”
服务器显示“GHIDEF”

我想你可以看到我来自哪里,我只需要一种清理 byte[] 数组的方法,就这方面而言。

下一步将是只读取我打算使用的字节,所以虽然我只使用了 X 量的数据,但实际上我收到的数据比我需要的要多得多,我需要现在处理最后的额外数据。

谁能建议我如何解决这个问题?

我的代码如下。

客户:

    static void Main(string[] args)
    {

        try
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            Console.WriteLine("Welcome to Josh's humble server.");
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 2000);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            sock.Bind(ipEnd);
            sock.Listen(100);
            Socket clientSock = sock.Accept();
            byte[] mabytes = encoding.GetBytes("Test");
            clientSock.Send(mabytes);
            Console.WriteLine("Hmmm, data sent!");
            Console.ReadLine();
            Console.WriteLine(encoding.GetString(mabytes));
            Console.ReadLine();
            byte[] buffer = encoding.GetBytes("server message");
            while (true)
            {
                clientSock.Receive(buffer);
                Console.WriteLine(encoding.GetString(buffer));
            }


        }
        catch (Exception ex)
        {
            Console.WriteLine(Convert.ToString(ex));
            Console.ReadLine();
        }

    }

服务器:
    static void Main(string[] args)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        Console.WriteLine("Welcome to Josh's humble client.");
        Console.ReadLine();
        IPEndPoint ipEnd = new IPEndPoint(ip, 2000);
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        sock.Connect(ipEnd);
        while (true)
        {
            Console.WriteLine("Please enter a message:\n");
            byte[] mabyte = encoding.GetBytes(Console.ReadLine());
            sock.Send(mabyte);
            Console.WriteLine("Sent Data");
        }
    }

提前致谢

最佳答案

您使用 clientSock.Receive(buffer); 获取数据但从不检查返回值。它可能读取小于缓冲区的长度。更正确的方法可以是:

int len = clientSock.Receive(buffer);
Console.WriteLine(encoding.GetString(buffer,0,len));

同样使用 byte[] buffer = encoding.GetBytes("server message"); 分配字节也不是一个好方法。
使用类似 byte[] buffer = new byte[1024*N]; 的东西

--编辑--

当多字节字符在连续读取之间拆分时,即使这种方法也可能会出现问题。
更好的方法是使用 TcpClient,通过 new StreamReader(tcpClient.GetStream()) 包装其流并逐行读取

关于C# 读取字节 [] 并删除垃圾数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13315991/

10-11 01:48
查看更多