2013-03-29 85 views
-1

我正在搭建C#的客户端,与Python中的服务器通信。客户端发送的文件使用Socket.send()方法服务器,并使用线程能够异步使用发送多个文件BackgroundWorker通过特定套接字发送了多少字节?

private void initializeSenderDaemon() 
{ 
    senderDaemon = new BackgroundWorker 
    { 
     WorkerReportsProgress = true, 
    }; 
    senderDaemon.DoWork += sendFile; 
} 

当某些条件得到满足,则RunWorkerAsync()方法被调用和文件被发送

客户端和服务器上的应答文件的大小之前开始转移

我希望能够跟踪多少文件已经从客户端发送

我虽然已经对这样的事情概念性代码,我知道这是行不通的

byte[] fileContents = File.ReadAllBytes(path); // original file 
byte[] chunk = null; // auxiliar variable, declared outside of the loop for simplicity sake 
int chunkSize = fileContents.Length/100; // we will asume that the file length is a multiplier of 100 for simplicity sake 

for (int i = 0; i < 100; i++) 
{ 
    chunk = new byte[chunkSize]; 
    Array.Copy(fileContents, i * chunkSize, chunk, i * chunkSize, chunkSize); 
    // Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length); 
    s.Send(chunk); 
    reportProgress(i); 
} 

reportProgress(100); 

有与该代码明显的问题,但我写它只是解释什么是我想要做的

¿如何跟踪一个特定文件已经发送到服务器的字节数? ¿有什么办法可以做到而不依赖于解决方法? ¿我应该使用套接字类中的其他方法吗?

谢谢!

+0

'fileContents.Length/100'不能授予整个文件将被发送! –

+0

什么是文件大小是101字节?你最终只会发送100个字节! –

+0

@AppDeveloper,我知道这一点,阅读我的意见。代码的第二部分只是概念 –

回答

0

尝试这样:

int bSent = 0; 
int fileBytesRead; 

FileStream fileStream = File.Open(tmpFilename, FileMode.Open, FileAccess.Read, FileShare.Read); 
while ((fileBytesRead = fileStream.Read(buffer, 0, BUFFER_SIZE)) > 0) 
{ 
    socket.Send(buffer, 0, fileBytesRead); 
    bSent += fileBytesRead; 

    arg.Progress = (int) (bSent*100/totalBytes); 
    arg.Speed = (bSent/sw.Elapsed.TotalSeconds); 
    OnProgress(arg); 
} 

这个回答是不是一个完美的答案,它只是从我的工作中提取,但会给你一个粗略的想法更好的方式使用套接字发送的文件!

+0

好的答案,但什么是'SW '在行 'arg.Speed =(bSent/sw.Elapsed.TotalSeconds);'? –

+0

@warcraker - 文件传输的速度,以字节/秒为单位。 –

+0

好吧,现在我看到它是一个'StopWatch' –