我正在实现一个websocket应用程序,它提供了一些实时数据。经过一些研究后,我想出了一个代码,它给了我想要的输出。但我知道这不是正确的做法。请提出任何建议,使其正确。
Server.js
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
}));
}
});
Client.js
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)
});
我是node.js和websocket的新手。帮助!