What we are going to do is to put the MySQL side of a table data update real-time push to the client, such as the MySQL side of the table data ABC becomes 123, then the use of the program will be the latest 123 push to each client connected to the server. If the server is connected to a client that is 0, that is, there is no client connection at this time, the program will not execute the push information code to avoid unnecessary resource consumption, when the client is connected to the start of the push. Demo code Everyone can go to the following download button to download. To run the MySQL module that we want to install first Nodejs to use:
install MySQL
For more information on the use of MySQL modules, please visit: https://github.com/felixge/node-mysql
Install the Socket.io module again:
Install Socket.io
For more information on the use of the Socket.io module, please visit: http://socket.io/new database Nodejs, table articles (you can also build the table on your existing database, modify the corresponding source code):
CREATE DATABASE ' Nodejs 'CHARACTERSET UTF8; Use ' Nodejs '; SHOW DATABASES; Use ' Nodejs '; CREATE TABLE TEXT TEXT TEXT);
Go to Nodejs-push-mysql directory to run Demo:
$ node Server.js
Test results:
- Open the browser input http://localhost:8080 (can open a few more, obviously can feel the real-time push effect)
- Log in to MySQL database using MySQL tool, modify data of articles table in database Nodejs
- Once the table data is saved, those open clients will receive the most recent changes
- client.html Source code:
Head> <title> use Nodejs to implement real-time push MySQL database up-to-date information to clients </title> <style>DD, DT {float: Left; Margin:0; padding:5px; Clear: both; Display:block; Width: -%; } DT {background: #ddd; } Time{color:gray; } </style> </Head> <body> < Time></ Time> <divID="Container">loading ...</div> <script src="Socket.io/socket.io.js"></script> <script src="Http://code.jquery.com/jquery-latest.min.js"></script> <script>//Create a WebSocket connectionvar socket = Io.connect ('http://localhost:8080'); //show the information on the DivSocket.on ('Notification',function(data) {var articleslist="<dl>"; $.each (Data.articles,function(index,article) {articleslist+="<dt>"+ Article.title +"</dt>\n"+"<dd>"+ Article.author +"\ n"+"<dd>"+ Article.description +"\ n" "</dd>"; }); Articleslist+="</dl>"; $('#container'). HTML (articleslist); $(' Time'). HTML ('Last update time:'+ data. Time); }); </script> </body>Establish a MySQL connection and modify the corresponding database information according to your environment var app = require (' http '). Createserver (handler), Io = require (' Socket.io '). Listen (APP), FS = require (' FS '), MySQL = require (' mysql '), Connectionsarray = [], connection = Mysql.createconnection ({host: ' Lo Calhost ', User: ' Root ', password: ' Root ', database: ' Nodejs ', port:3306} ', polling_interval = +, Polli ngtimer;//Check that the database connection is normal connection.connect (function (ERR) {//does not appear error message, which indicates that the database connection succeeded Console.log (err);}); /Start HTTP service, bind port 8080app.listen (8080),//Load Client Home function handler (req, res) {fs.readfile (__dirname + '/client.html '), function (err, data) {if (err) {Console.log (err); Res.writehead (500); return Res.end (' Loading the client home page has an error ... '); } res.writehead (200); Res.end (data); });} /* This is the way to implement the main function, the interval of 3 seconds to query the database table, updates are pushed to the client */var Pollingloop = function () {//query database var queries = Connection.query (' SELECT * from articles '), articles = []; Used to save query results//query results listen to query. On (' Error ', function (err) {//Query error handling consOle.log (ERR); Updatesockets (ERR); }). On (' Result ', function (user) {//Add the query to the result to the articles array Articles.push (user); }). On (' End ', function () {//Check if there is a client connection, continue querying database if (connectionsarray.length) {Pollingtimer = set Timeout (Pollingloop, polling_interval); Updatesockets ({articles:articles}); } });};/ /Create a WebSocket connection, real-time Update data io.sockets.on (' Connection ', function (socket) {Console.log (' current number of connected clients: ' + Connectionsarray.length); There are clients connected to the time to query, otherwise it is a waste of resources if (!connectionsarray.length) {pollingloop (); } socket.on (' Disconnect ', function () {var socketindex = connectionsarray.indexof (socket); Console.log (' socket = ' + Socketindex + ' disconnected '); if (socketindex >= 0) {connectionsarray.splice (Socketindex, 1); } }); Console.log (' There is a new client connection! '); Connectionsarray.push (socket);}); var updatesockets = function (data) {//Plus latest update time data.time = new Date (); Push the latest update information to the client that is so connected to the server ConnectionsarRay.foreach (function (tmpsocket) {tmpSocket.volatile.emit (' notification ', data); });};
Demo download