C# 从TCP套接字接收不完整的文件

C# 从TCP套接字接收不完整的文件,c#,file,sockets,tcp,sendfile,C#,File,Sockets,Tcp,Sendfile,我正在编写服务器客户端应用程序,但在发送文件时遇到问题;有时传输是正确完成的,但通常情况下,似乎服务器和接收器接收的字节较少,并在客户端已完成发送所有文件时继续等待其他数据 这是发件人: public void sendFile(String path) { FileInfo fi = new FileInfo(path); long fileDim = fi.Length; //Console.ReadLine(); writ

我正在编写服务器客户端应用程序,但在发送文件时遇到问题;有时传输是正确完成的,但通常情况下,似乎服务器和接收器接收的字节较少,并在客户端已完成发送所有文件时继续等待其他数据

这是发件人:

public void sendFile(String path) {
        FileInfo fi = new FileInfo(path);
        long fileDim = fi.Length;

        //Console.ReadLine();

        writer.WriteLine(Convert.ToString(fileDim));
        socket.SendFile(path);

    }
这是接收器:

public bool receiveFile(String path) {
        byte[] recievedData = new byte[1024];
        int bytesRead;

        long fileDim = Convert.ToInt64(reader.ReadLine());

        if (!Directory.Exists(Path.GetDirectoryName(path)))
            Directory.CreateDirectory(Path.GetDirectoryName(path));

        BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Append));

        try {
            while (fileDim > 0) {
                bytesRead = socket.Receive(recievedData, recievedData.Length, SocketFlags.None);
                bw.Write(recievedData, 0, bytesRead);
                fileDim -= bytesRead;
            }
        }
        finally {
            bw.Close();
        }
    }
如果我取消对发送者的Console.ReadLine的注释,那么在他发送文件之前,我会停止它几秒钟,一切正常。 所以看起来,若发送方速度太快,一些数据就会丢失,但我知道在TCP流中这是不可能的……那个么为什么会发生这种情况呢


请帮助我,提前谢谢

我想作者是新的StreamWriternew NetworkStreamsocket还是什么?fileDim的值是否包含预期值?是的,writer是StreamWriter,reader是StreamReader,fileDim总是以预期值到达接收器