文件传输仅在第一次成功,经常失败

时间:2012-01-23 00:22:10

标签: c# .net sockets tcp file-transfer

  • 这是使用套接字TCP的文件传输发送/接收程序。此代码包含在客户端和服务器应用程序中,并且它仅在第一次正常工作。

  • 第二次,将要接收的一方获得0并且转移结束。如何修复它以便可以多次使用?

    public static void sendFile(string filePath)
    {
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        string fileName = Path.GetFileName(filePath);
        byte[] fileData;
        try
        {
            //sending file name and file size to the server
            busy = true;
            fileSize = fs.Length;
            byte[] fileDetial = null;
            string detail =  fileName + "," + fileSize.ToString();
            fileDetial = Encoding.ASCII.GetBytes(detail);
            client.Send(fileDetial);
    
            //sending file data to the server
    
            fileData = new byte[packetSize];
            count = 0;
            sum = 0;
            Program.thFP.Start();                           // running transfer rate
            Program.fp.StatusLabel("Sending data...");
            transferRate.timeLeft();
    
            while (sum < fileSize)
            {
                fs.Seek(sum, SeekOrigin.Begin);
                fs.Read(fileData, 0, fileData.Length);
                count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
                sum += count;
                Program.fp.ProgressBarFileHandler(sum, fileSize);
            }
        }
        finally
        {
            busy = false;
            fs.Close();
            fileData = null;
            MessageBox.Show(string.Format("{0} sent successfully", fileName));
        }
    }
    

    根据我的猜测,下面的代码完全没有问题..我认为问题出在SENDFILE方法中..但是这里是receiveFile代码..它可能有帮助

    public static void ReceiveFile()
    {
    
        //receving file name and file size from server
        busy = true;
        byte[] commandData = new byte[1024];
        client.Receive(commandData);
        Console.WriteLine(Encoding.ASCII.GetString(commandData));
        string[] Command = Encoding.ASCII.GetString(commandData).Split(',');
        string fileName = Command[0];
        fileSize = Convert.ToInt64(Command[1]);
        Program.thFP.Start();                           // running transfer rate
        Program.fp.StatusLabel("Receiving data...");
        transferRate.timeLeft();
    
        // receiving the file data from server
        FileStream fs = new FileStream(@"D:\" + fileName, FileMode.Create, FileAccess.Write);
        byte[] fileData = new byte[packetSize];
        try
        {
            count = 0;
            sum = 0;
            while (sum < fileSize)
            {
                count = client.Receive(fileData,0,fileData.Length, SocketFlags.None);
                fs.Seek(sum, SeekOrigin.Begin);
                fs.Write(fileData, 0, fileData.Length);
                sum += count;
                Program.fp.ProgressBarFileHandler(sum,fileSize);
            }
        }
        finally
        {
            busy = false;
            fs.Close();
            fileData = null;
            MessageBox.Show(string.Format("{0} recevied successfully", fileName));
        }
    }
    
  • 2 个答案:

    答案 0 :(得分:1)

    我修好了代码。问题出在SendFile方法中,完全在FileStream

    我应该处理它,所以我可以使用新路径再次初始化它

    finally
    {
        busy = false;
        fs.Dispose();   //here i fixed my mistake it was fs.Close()
        fileData = null;
        MessageBox.Show(string.Format("{0} sent successfully", fileName));
    }
    

    答案 1 :(得分:0)

    我建议你需要处理FileStream。我建议将它包装在一个使用块中,因此即使抛出一个重复也会一直处理它。

    // receiving the file data from server
    using (FileStream fs = new FileStream(@"D:\" + fileName, FileMode.Create, FileAccess.Write))
    {
        byte[] fileData = new byte[packetSize];
        try
        {
            ...same code as before here...
        }
        finally
        {
             ...same code as before here...
        }
    }
    

    我总是建议在使用块中包装流。这意味着如果您以后再回来编辑代码,那么引入代码路径的危险就会降低,该代码路径在完成后不会丢弃流。

    我还要重构代码,以便你的“成功”消息不在finally块中 - 它可能应该在try块的末尾。当抛出异常时,您当前的实现将显示Success消息 - 因此文件可能会成功。