nodejs socket.io doing nothing but connections 100% cpu

时间:2015-10-30 22:48:46

标签: node.js sockets socket.io

I'm new to nodeJs and socket.io, when I run it it reaches cpu 100% (the cpu is jumping between 14-103%..) when I have about 800 users in the site. At first the problem I saw was that every few minutes all of the users disconnected and reconnect after few seconds, so I commented out all of the code ended up with on connect and on disconnect.. still after 5 minutes cpu reaches jumping cpu 14-100%.. I don't know what to check since there's laterally nothing but the most basic stuff.. node version - 0.10.25 socket.io version - 1.0 code snippet -

var redis = require('redis').createClient(),
    server = require('http').createServer(),
    request = require('request'),
    io = require('socket.io').listen(server),
    sockets = {};
//  , memcache = require('memcache')
//  , cookie = require('cookie')

// run HTTP server on this port
server.listen(3000);

console.log('started node sockets.');

// only allow authenticated connections - TODO: check if its doing anything.. :x
io.set('authorization', function(handshake, callback)
{
  return callback(null, true);

});

io.sockets.on('connection', function(socket)
{
  var id = getUserId(socket);
  if( id === false) return;
// store user's socket
  sockets[id] = socket;
  console.log('User ' + id + ' connected');
  request({url:"http://www.-----.co/nodeConnect", qs:{id: id}},function(){})


  socket.on('disconnect', function()
  {
    id = getUserId(socket);
    if( id === false ) return;
// store user's socket
    delete sockets[id];
    console.log('User ' + id + ' disconnect');
    request({url:"http://www.----.co/nodeDisconnect", qs:{id: id}},function(){});

});

function getUserId(socket) {
  if( typeof socket.handshake.headers.cookie == 'undefined' ) return false; // HOTFIX - check it
  var cookie = socket.handshake.headers.cookie;
  var startAt = cookie.indexOf('; uid=') + 6;
  var tempUid = cookie.substr(startAt);
  return tempUid.substr(0, tempUid.indexOf(';') ); // return id.
}

the server is a very strong server 32cpu, 120gb ram. running nginx, php, nodejs, for about 1000 ppl.. and should I check to get this running without eating all of my cpu? and btw, how much cpu is this node application actually should use?

1 个答案:

答案 0 :(得分:1)

问题是连接和断开连接中的请求,它们很慢,而且由于大量流量,CPU太占用了。