【发布时间】:2013-05-30 08:40:35
【问题描述】:
- 原始原生 tcp 服务器 我用一个客户端测试代码并发长连接服务器,什么都不做。 连接 5w 后我关闭了 client.js,但是服务器端会有大约 100M 内存没有释放。
服务器代码:
var net = require('net');
var server = net.createServer(function(client) {
console.log('server connected');
client.on('data',function(){});
client.on('end',function(){console.log('end');});
});
server.listen(8124, function() {
console.log('server bound');
});
客户端代码:
var net = require('net');
var host = '192.168.0.110'
// var host = "localhost"
, port = 8124
for(var i=0; i < 50000; i++){
var client = net.connect({host: host, port: port},
function(i){
return function() { //'connect' listener
var num = i;
console.log('client connected ' + num);
}}(i)
);
client.on('end',function(){
console.log('end');
client.end()
})
}
客户端在另一台机器上
2、长循环
var a = b = c = d = [];
console.log((process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2), 'Mb');
for(i=0;i<50000;i++){
a.push(new Date());
b.push(new Date());
c.push(new Date());
d.push(new Date());
}
console.log((process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2), 'Mb');
a = null;
b = null;
c = null;
d = null;
console.log('null');
console.log((process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2), 'Mb');
console.log((process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2), 'Mb');
setInterval(function(){
console.log((process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2), 'Mb');
},5000);
我将变量设置为空,但内存没有释放。 有人告诉我使用 process.nextTick 来防止长循环 但还是不行。
【问题讨论】:
-
您正在尝试对服务器施加压力,或者您想知道如果达到 50k 并发服务器,您的服务器会发生什么? @miktam 说的是正确的,您必须等待 GC 清除内存。如果你的服务器真的达到了 50k 并发用户,我建议你扩展你的服务器以避免内存泄漏。
标签: javascript node.js memory v8