通过TCP发送文件时有很多额外的空字节

时间:2017-01-14 04:07:09

标签: c#

过去几天我一直在学习如何在C#中使用TcpClients,并且能够通过tcp发送字符串(消息)。今天,我决定尝试发送一个文本文件(即,客户端将接收该文件并将其写入同一文件夹)。它有效,除了一个问题 - 消息后有一个空字节的TON。这就是我的意思:

原始文本文件内容:http://i.imgur.com/UCO3jvL.png

收到文本文件内容:http://i.imgur.com/6vucz40.png

我查看了收到的文件的大小,长度为65536个字符。我知道TCP数据包的最大大小是65535,所以我所想的是我的代码中的某些东西导致它使用数据包的最大大小而不是它所需的数量。

这是我的服务器代码,它将文件发送到客户端:

        if(message.Contains("getFile"))
        {
            byte[] fileBytes = File.ReadAllBytes("text.txt");
            stream.Write(fileBytes, 0, fileBytes.Length);
        }

这是我的客户端代码,它从服务器接收文件并将其写入磁盘:

        if(command.Contains("getFile"))
        {
            byte[] readBuffer = new byte[client.ReceiveBufferSize];
            int data = stream.Read(readBuffer, 0, readBuffer.Length);
            File.WriteAllBytes("file.txt", readBuffer);
        }

1 个答案:

答案 0 :(得分:2)

您的问题是您完全无视从网络获取的数据量,即使您跳过网络而只是这样做:

byte[] readBuffer = new byte[client.ReceiveBufferSize];
File.WriteAllBytes("file.txt", readBuffer);

你最终会得到一堆零的文件。

您需要考虑stream.Read的返回值:

using (BinaryWriter binWriter = new BinaryWriter(File.Open("file.txt", FileMode.Create)))
{
   binWriter.Write(readBuffer, 0, data);
}