HttpWebRequest का उपयोग करते समय बैंडविड्थ उपयोग को सीमित कैसे करें?HttpWebRequest का उपयोग करते समय बैंडविड्थ उपयोग को सीमित कैसे करें?
9
A
उत्तर
0
आप बैंडविड्थ-सीमित HTTP प्रॉक्सी में Proxy property को हुक कर सकते हैं, उदाहरण के लिए Squid can do this। शायद एक सुविधाजनक समाधान नहीं है, लेकिन यह निश्चित रूप से काम करेगा।
1
आप मैं आरएक्स की तरह कुछ का उपयोग करना चाहिये को आसान बनाने में टाइमर उपयोग आदि
class Uploader
{
/// <summary>Thread-safe flag to ensure that a packet isn't currently sending</summary>
private volatile bool isPacketSending = false;
/// <summary>
/// HTTP Posts a stream to a web address with a maximum bytes per second until the file is uploaded
/// </summary>
/// <param name="address">The web address to post the file to</param>
/// <param name="requestBody">The request body to stream at a maximum speed</param>
/// <param name="bytesPerSecond">The maximum number of bytes to send every second</param>
/// <returns>Returns an observable sequence of the bytes read so far</returns>
public IObservable<long> PostStreamThrottledAsync(Uri address, Stream requestBody, int bytesPerSecond)
{
if (!requestBody.CanRead)
{
throw new InvalidOperationException("Request body stream cannot be read from");
}
return Observable.Using(
() =>
{
var client = new WebClient();
return client.OpenWrite(address);
},
outputStream => Observable.Return(0L).Concat(Observable.Interval(TimeSpan.FromSeconds(1)))
.TakeWhile(tick => SendPacket(requestBody, outputStream, bytesPerSecond) != 0)
.Select(_ => requestBody.Position));
}
/// <summary>
/// Sends a packet up to the maximum bytes specified
/// </summary>
/// <param name="requestBody">The stream to read from</param>
/// <param name="output">The stream to write to</param>
/// <param name="bytesPerSecond">The number of bytes to send</param>
/// <returns>Returns the number of bytes actually sent; zero if at end of stream; -1 if we are exceeding throughput capacity.</returns>
private int SendPacket(Stream requestBody, Stream output, int bytesPerSecond)
{
if (isPacketSending)
{
return -1;
}
try
{
isPacketSending = true;
var buffer = new byte[bytesPerSecond];
var bytesRead = requestBody.Read(buffer, 0, bytesPerSecond);
if (bytesRead != 0)
{
output.Write(buffer, 0, bytesRead);
}
return bytesRead;
}
finally
{
isPacketSending = false;
}
}
}
मुझे यह पसंद मदद करने के लिए कोड में यह कर रहे हैं। मुझे अपने खुद के थ्रॉटलर को थोड़ा सा मूर्खतापूर्ण लग रहा है :) – Tom
प्रश्न यह है कि कोड को हल करने के तरीके के बारे में सवाल यह है कि इसे प्राप्त करने के लिए किसी अन्य बाहरी उपकरण का उपयोग कैसे करें। – SeriousM