我得到了那个漂亮的应用程序,现在我要计算一些我想知道的场景 应用程序本身为每个会话生成多少入站/出站流量。 我不想使用浏览器,而是从服务器端收集信息。
nodejs net.server没有任何符合描述的方法, 我发现只有net.socket方法:
socket.bytesRead
接收的字节数。
socket.bytesWritten
发送的字节数。
他们是否适用于通过net.server生成的流量? 任何收集这种统计数据的现有node_modules?
提前致谢
答案 0 :(得分:3)
嗯,那是因为net.server
使用了net.socket
。要获得总计,您必须在套接字关闭后将bytesRead
和bytesWritten
添加到总计中。例如:
const net = require("net");
var server = net.createServer(function (c) {
c.on('close', function () {
// add to the totals
server.bytesSent += c.bytesWritten;
server.bytesReceived += c.bytesRead;
});
c.write('Hello world!\r\n');
c.pipe(c);
c.end();
});
server.bytesReceived = 0;
server.bytesSent = 0;
server.listen(3000);
var time = process.hrtime();
setInterval(function (){
process.stdout.write('\u001B[2J\u001B[0;0f');
var diff = process.hrtime(time)[0] + process.hrtime(time)[1]/1000000000;
var bpsSent = Math.round(server.bytesSent/diff) || 0;
var bpsReceived = Math.round(server.bytesReceived/diff) || 0;
console.log("Running node.js %s on %s-%s", process.version, process.platform, process.arch);
console.log("Memory usage: %d bytes", process.memoryUsage().rss);
console.log("Uptime: %ds", Math.round(process.uptime()));
console.log("Open connections: %d", server.connections);
console.log("In: %d bytes (%d bytes/s)", server.bytesReceived, bpsReceived);
console.log("Out: %d bytes (%d bytes/s)", server.bytesSent, bpsSent);
}, 100);
如果您需要实时更新总计(当接收/发送数据时),您可以在写入/读取时将缓冲区的长度直接添加到总计中。当你的插座长时间打开并传输大量数据时,这一点尤其有用。
var server = net.createServer(function (c) {
var oldWrite = c.write;
c.write = function(d) {
if (!Buffer.isBuffer(d)) {
d = new Buffer(d);
}
oldWrite.call(this, d);
server.bytesSent += d.length;
};
c.on('data', function(d){
server.bytesReceived += d.length;
});
c.write('Hello world!\r\n');
c.pipe(c);
c.end();
});