2011-12-31 198 views
3

低于我的socket服务器工作正常3-4天,但经过DAT我从穆宁得到,它的超出规定范围的CPU(160)的通知。听起来好像内存是不是免费的:D正确,但我找不到在哪里?Socket.io节点服务器

var io = require('socket.io').listen(80); 
var Memcached = require('memcached'); 
var md5 = require('MD5'); 
var memcached = new Memcached(['IP']); 
var interval_time = 5000; 

loglevel = process.argv[2]; 
if(loglevel == "") loglevel = 1; 

io.enable('browser client minification'); // send minified client 
io.enable('browser client etag');   // apply etag caching logic based on version number 
io.enable('browser client gzip');   // gzip the file 

io.sockets.on('connection', function (socket) 
{ 
    socket.on('get_notifications', function (data) 
    { 
     // verify authorization 
     if(data.key == 'XXXXXXX') 
     { 
      socket.user_id = data.user_id; 

      setInterval(function() 
      { 
       memcached.get(["ntf_" + socket.user_id, "nnt_" + socket.user_id], function(error, mem_result) 
       { 
        num_orders = mem_result['ntf_' + socket.user_id]; 
        is_searching = mem_result['nnt_' + socket.user_id]; 

        if(typeof(socket.prev_notification)==='undefined') socket.prev_notification = {}; 

        var notification = socket.prev_notification; 
        var have_new_notifications = false; 

        if(is_searching != socket.prev_notification.nnt) 
        { 
         have_new_notifications = true; 
         notification.nnt = is_searching; 
        } 

        if(num_orders != socket.prev_notification.ntf) 
        { 
         have_new_notifications = true; 
         notification.ntf = num_orders; 
        } 

        if(have_new_notifications) 
        { 
         var today=new Date(); 
         var h=today.getHours(); 
         var m=today.getMinutes(); 
         var s=today.getSeconds(); 

         console.log(h+":"+m+":"+s+' - sending notification to ' + data.user_id); 
         console.log(notification); 

         socket.emit('notifications', notification); 
         socket.prev_notification = notification; 
        } 
       }); 
      }, interval_time); // interval 
     } 
    }); 
}); 

回答

2

我认为问题是,你火每get_notification事件被触发时setInterval。这些间隔永远不会停止,一旦他们开始工作。

你应该写一些代码,当某些条件满足时会停止这些间隔(timeout?client disconnect?whatever)。或更改setIntervalsetTimeout时会触发本身,除非抛出异常(如例如不能发送数据到断开客户端)。

+0

嗯,我会尝试更改为'setTimeout',并在几天内回覆。谢谢:) – Christoffer 2011-12-31 11:43:25

+0

这解决了我的问题:) – Christoffer 2012-01-04 17:24:46