Bandwidth Throttling a Stream in a HttpWebRequest PUT

578 views
Skip to first unread message

jbgillet

unread,
Jan 5, 2010, 5:38:24 PM1/5/10
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Hi, I am building a client program that uploads a file to a server via
a HttpWebRequest PUT.

Basically i would like to throttle this - I want to limit the upload
speed on the client side. I have looked around and have not been able
to find the answer. If i need to use a different method of uploading
then so be it, but here is the code i am using which is working fine:

'create local file stream
Dim rdr As New FileStream(fileToUpload, FileMode.Open)

Dim webReq As HttpWebRequest = DirectCast(WebRequest.Create
(uploadLocation), HttpWebRequest)
webReq.Method = "PUT"
webReq.ContentLength = rdr.Length
webReq.AllowWriteStreamBuffering = True

Dim reqStream As Stream = webReq.GetRequestStream()
Dim inData As Byte() = New Byte(rdr.Length - 1) {}

' Get data from upload file to inData
Dim bytesRead As Integer = rdr.Read(inData, 0, rdr.Length)

' put data into request stream
reqStream.Write(inData, 0, rdr.Length)

rdr.Close()

If anyone happens to know of anything, even if it points me in the
right direction, that would be great.
Thanks heaps.
John

ThanderMaX

unread,
Jan 7, 2010, 11:46:14 AM1/7/10
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
What about instead of writing whole file content in a single go as
in :

reqStream.Write(inData, 0, rdr.Length)

write chunk data and calculate the amount of data to send per sec :


int totlen = rdr.Length;

'let X be the transfer rate in kb/sec
'then single block size will be :

int chunklen = 1024 * x ;
int pos = 0;

'then send the chunked data :

'Call the following function from a timer event with interval set to
1000 ms , say timer1

void SendChunk(chunklen)
{
int isend = reqStream.Write(_bGetBytesRange(inData, pos, chunklen),
0,chunklen) ;

pos += isend;

if (pos >= totlen ) //verify the logic :)
{
timer1.Stop();
}

}

/* Remember the above code may not be accurate 100% but atleast give u
90% accuracy */.

ThanderMaX

unread,
Jan 7, 2010, 11:51:57 AM1/7/10
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
One typo :

instead of


int isend = reqStream.Write(_bGetBytesRange(inData, pos, chunklen),
0,chunklen) ;

it should be :

int isend = reqStream.Write(inData, pos, chunklen);

Also need to check boundary conditions in all place.

Reply all
Reply to author
Forward
0 new messages