Note that there are some explanatory texts on larger screens.

plurals
  1. POReal time updation using node.js and websocket
    text
    copied!<p>I am implementing an websocket application which gives some real time data. After some research i came up with a code which gives me the desired output. But i know this is not the correct way of doing this. Please give any suggestion to make it right.</p> <p><strong>Server.js</strong> </p> <pre><code>var http = require('http'); var server = http.createServer(function (request, response) { response.writeHead(404); response.end(); }); var port = 8889; server.listen(port, function () { console.log('server is listening on port ' + port); }); var WebSocketServer = require('websocket').server; wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); var mysql = require('mysql'); var _livedata; var db_con = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database: 'dev_db' }); function getLiveData() { db_con.query('SELECT * from live_data', function (err, rows, fields) { //* if (err) throw err; _livedata = rows[0]; }); } setInterval(getLiveData, 2000); // update _livedata wsServer.on('request', function (request) { var connection = request.accept('chat', request.origin); setInterval(sendLiveData, 5000); // sends updated _livedata function sendLiveData() { connection.sendUTF(JSON.stringify({ data: _livedata })); } }); </code></pre> <p><strong>Client.js</strong></p> <pre><code> socket = new WebSocket("ws://localhost:8889", 'chat'); socket.addEventListener("open", function () { var a = socket.send(JSON.stringify("Please send data")); }); socket.addEventListener('message', function (data) { var parsedData = JSON.parse(data.data).vehicle; console.log(parsedData) }); </code></pre> <ul> <li>live_data table is updated every 5 seconds.</li> </ul> <p>I am very new to node.js and websocket. Help!!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload