C#读取一个byte []并删除垃圾数据

Xtr*_*osh 2 c# sockets

无法在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();
        }

    }
Run Code Online (Sandbox Code Playgroud)

服务器:

    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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢

L.B*_*L.B 5

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

int len = clientSock.Receive(buffer);
Console.WriteLine(encoding.GetString(buffer,0,len));
Run Code Online (Sandbox Code Playgroud)

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

- 编辑 -

当在连续读取之间分割多字节字符时,甚至这种方法也会有问题.一种更好的方法是使用TcpClient,包装其流new StreamReader(tcpClient.GetStream())并逐行读取