title: Socket.io for checking updates from database
body: <p>I have a node.js server that connects to a mysql database and opens up a new socket using socket.io. The role of this server is basically to notify any client (user) that connects to it when there's a new message for that user in the database table. The code below only works if the client explicitly emits a 'check_messages' request. How can I change it so that the client is the one that's notified whenever a new message is inserted in the mysql table for that user instead of the client having to explicitly emit a 'check_messages' request?</p>
  
  <pre><code>var app = require('http').createServer().listen(8124);
  
  var mysql      = require('mysql');
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'some username',
    password : 'some password',
    database : 'some database'
  });
  
  connection.connect();
  
  console.log('Server running at http://127.0.0.1:8124/');
  
  var io = require('socket.io').listen(app);
  
  var prev_id = 0;
  
  io.sockets.on('connection', function (socket) {
    socket.emit('greeting', 'Hello');
    socket.on('check_messages',function(data){
    var uid = data['uid'];
    var q = "SELECT * FROM messages WHERE user_id=" + uid + " ORDER BY id DESC LIMIT 1";
    connection.query(q, function(err, rows, fields) {
        if (err) throw err;
        if (rows[0].id &gt; prev_id){
          socket.emit('new_message',rows[0]);
          prev_id = rows[0].id
        }
      });
    });
  });
  </code></pre>