Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io for checking updates from database

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?

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 > prev_id){
        socket.emit('new_message',rows[0]);
        prev_id = rows[0].id
      }
    });
  });
});
like image 996
niravb Avatar asked May 10 '13 00:05

niravb


People also ask

Which is better Socket.IO or WS?

Both WebSocket vs Socket.io are popular choices in the market; let us discuss some of the major Difference Between WebSocket vs Socket.io: It provides the Connection over TCP, while Socket.io is a library to abstract the WebSocket connections. WebSocket doesn't have fallback options, while Socket.io supports fallback.

What can Socket.IO be used for?

Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and server. It has two parts: a client-side library that runs in the browser, and a server-side library for node.

What is the difference between Socket.IO and socket IO client?

socket-io. client is the code for the client-side implementation of socket.io. That code may be used either by a browser client or by a server process that is initiating a socket.io connection to some other server (thus playing the client-side role in a socket.io connection).

Does Socket.IO reconnect automatically?

In the first case, the Socket will automatically try to reconnect, after a given delay.


2 Answers

If you don't want to do any polling on the database you can use the postgresql database which support listen/notify. You will be notified immediately when there is a modification on the table.

like image 145
leszek.hanusz Avatar answered Sep 20 '22 15:09

leszek.hanusz


You can run your code in timer's event handler on server.

The code below checks database for new message for every 5 seconds and emits event if necessary

io.sockets.on('connection', function (socket) {
  socket.emit('greeting', 'Hello');
  setInterval(5000,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 > prev_id){
        socket.emit('new_message',rows[0]);
        prev_id = rows[0].id
      }
    });
  });
});

As alternative way I think you could implement message queueing using redis with the fast node_redis client. It has built-in pubsub semantics.

Look at Redis. It is fast NoSQL key-value storage which you can use to organize fast message queueing. Use node_redis npm module to communicate with it. Read this reference

like image 26
zavg Avatar answered Sep 20 '22 15:09

zavg