【发布时间】:2019-09-07 15:27:44
【问题描述】:
我正在尝试限制 HTTP 请求使用的带宽(下载/上传速度)。我正在使用 NPM 包stream-throttle。我创建了一个自定义的HTTP agent 来通过 Throttle 实例来管道套接字,并计算了 5MB 文件的下载速度。
const http = require("http");
const net = require("net");
const {Throttle, ThrottleGroup} = require("stream-throttle");
const maxBandwidth = 100;
// an example 5MB file of random data
const str = "http://212.183.159.230/5MB.zip";
// this pipes an instance of Throttle
class SlowAgent extends http.Agent {
createConnection(options, callback){
const socket = new net.Socket(options);
socket.pipe(new Throttle({rate: maxBandwidth}));
socket.connect(options);
return socket;
}
}
const options = {
// this should slow down the request
agent: new SlowAgent()
};
const time = Date.now();
const req = http.request(str, options, (res) => {
res.on("data", () => {
});
res.on('end', () => {
console.log("Done! Elapsed time: " + (Date.now() - time) + "ms");
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.on("end", () => {
console.log("done");
});
console.log("Request started");
req.end();
不管maxBandwidth 的值是多少,或者是否使用了SlowAgent(我已经尝试注释掉agent: new SlowAgent()),我注意到经过的时间(大约4000 毫秒)没有区别。如何修复我的 SlowAgent 类? socket.pipe我听不懂吗?或者我还有什么需要做的吗?
怪异的pointed out 将SlowAgent 更改为:
// this pipes an instance of Throttle
class SlowAgent extends http.Agent {
createConnection(options, callback){
const socket = new net.Socket(options);
socket.connect(options);
return socket.pipe(new Throttle({rate: 10}));
}
}
但这会导致这个问题:
problem with request: Parse Error: Expected HTTP/ Error: Parse Error: Expected HTTP/
at Throttle.socketOnData (_http_client.js:456:22)
at Throttle.emit (events.js:209:13)
at addChunk (_stream_readable.js:305:12)
at readableAddChunk (_stream_readable.js:286:11)
at Throttle.Readable.push (_stream_readable.js:220:10)
at Throttle.Transform.push (_stream_transform.js:150:32)
at /home/max/Documents/Personal/node-projects/proxy/node_modules/stream-throttle/src/throttle.js:37:14
at processTicksAndRejections (internal/process/task_queues.js:75:11) {
bytesParsed: 0,
code: 'HPE_INVALID_CONSTANT',
reason: 'Expected HTTP/',
rawPacket: <Buffer 47>
}
【问题讨论】:
-
您应该在您的
createConnection中添加return socket.pipe(new Throttle({rate: maxBandwidth}));,不是吗?目前您使用管道但不使用另一个(节流)端。请检查一下,让我知道它是否有效(现在无法测试)。 -
@freakish 我在尝试此操作时遇到错误(请参阅我的编辑)。