本文介绍了nodejs,socket.io简单代码内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用nodejs和socket.io为一个简单的套接字应用程序编写了下面的代码(只需connect和断开连接),大约50个用户的内存使用量并没有太大变化,但是最多300个用户,一个小时后,内存使用量仅为长大(server.js进程接近300MB并随着时间的流逝而增长),看来nodejs不会释放内存.

i wrote code bellow using nodejs And socket.io for a simple socket application (just connect and disconnect ), for about 50 user memory usage not change to much , but for up to 300 user and after one hour , memory usage just grow up ( near 300MB for server.js proccess and grows by time pass ) , it's look like that nodejs don't release memory.

var server = require('http').createServer();
var io = require('socket.io')(server);
var port = 9090;
var sockets = {};

server.listen(port, function () {
    console.log('Server listening at port ', port);
    //timer and logs are not problem , i tested it before.
    setInterval(function(){
      console.log(Object.keys(sockets).length+' Online Devices At '+Date());
    }, 1000 * 60 * 1);
});

io.on('connection',function(socket){
    sockets[socket.id]={id:socket.id};
    console.log('connected '+socket.id + ' count ' + Object.keys(sockets).length);
    socket.on('disconnect', function (data) {
        delete sockets[socket.id];
        console.log('disconnected '+socket.id+ ' count ' +Object.keys(sockets).length);
    });
});

我做错了什么吗?!

修改

使用forever启动文件后的14小时

14 hours after starting file with forever

300个开放的套接字以及大约500MB的内存使用量,这与我的nodejs进程有关.

300 open sockets And About 500MB of memory usage that is related to my nodejs proccess.

修改

16小时后,连接了300个插座进程停止后.

After 16 Hours , 300 Connected SocketsAfter process stopped.

ٍ编辑

请掠夺我的新代码.

var server = require('http').createServer();
var io = require('socket.io')(server);
var port = 90;
var counter = 0;
var clients = {}
server.listen(port, function () {
        console.log('Server listening at port ', port);
});
io.on("connection",function(socket){
        clients[socket.id] = socket;
        counter++;

        socket.on('disconnect', function (data) {
                counter--;
                delete clients[socket.id];
        });
});

我正在与1000个已连接用户进行尝试(另一台服务器正在模拟用户请求并打开套接字)

i am trying this with 1000 connected user ( another server is simulate user requests and open sockets )

开始前的内存使用量:100MB, 5分钟后和1000个稳定的打开连接后:400MB

memory usage before start :100MB , after 5 minutes and 1000 stable open connections : 400MB

推荐答案

在释放未使用的内存时,V8是惰性的,因此当V8实际上不运行其垃圾回收器时,它看起来就像是内存泄漏.要查看是否是这种情况,请在--expose-gc标志设置为例如

V8 is lazy when it comes to freeing up unused memory, so it may look like a memory leak when it is actually just V8 not running its garbage collector. To see if this is the case, run your process with the --expose-gc flag set e.g.

node --expose-gc yourscript.js

并强制间隔一定时间(我使用30秒间隔)进行手动垃圾收集.

And force manual garbage collection on an interval (I used 30 second interval).

setInterval(function(){
  global.gc();
  console.log('GC done')
}, 1000*30);

这篇关于nodejs,socket.io简单代码内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 12:57