websockets and database updates (push on change)
So my question: How can I achieve to get real-time data changes from a table of the database or from a certain query...
There is a module to watch for MySQL events: mysql-events
Official Example :
var MySQLEvents = require('mysql-events');var dsn = { host: _dbhostname_, user: _dbusername_, password: _dbpassword_,};var mysqlEventWatcher = MySQLEvents(dsn);var watcher =mysqlEventWatcher.add( 'myDB.table.field.value', function (oldRow, newRow, event) { //row inserted if (oldRow === null) { //insert code goes here } //row deleted if (newRow === null) { //delete code goes here } //row updated if (oldRow !== null && newRow !== null) { //update code goes here } //detailed event information //console.log(event) }, 'match this string or regex');
... which will send the update to all clients, that are connected in real-time, without long polling?
You can use socket.io and prevent the initial http polling entirely by doing this on the client:
var socket = io({transports: ['websocket'], upgrade: false});
To avoid clients from using polling, add this line to the server:
io.set('transports', ['websocket']);
and to send the events to all connected (socket.io) clients from mysql-event
use the following :
io.sockets.emit('db-event',eventDataObj)