1

我正在实现一个 websocket 应用程序,它提供了一些实时数据。经过一些研究,我想出了一个代码,它给了我想要的输出。但我知道这不是正确的做法。请提出任何建议以使其正确。

服务器.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
        }));
    }
});

客户端.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) 
});
  • live_data 表每 5 秒更新一次。

我对 node.js 和 websocket 很陌生。帮助!!

4

0 回答 0