2011-12-31 159 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