通过特定套接字发送了多少字节?

时间:2013-03-29 15:32:46

标签: c# sockets

我正在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);

该代码存在明显的问题,但我写的只是为了解释我想要做什么

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

谢谢!

1 个答案:

答案 0 :(得分: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);
}

这个答案不是一个完美的答案,它只是我作品的摘录,但会给你一个粗略的想法,更好的方法来使用套接字发送文件!