Friday, 26 May 2017

Send different data to same client with nodejs

i have a problem with my NodeJS application. I want to send differents data on one client. I have realtime data from a Java program, and i have data from a database. That's work, i see two data but i want to send realtime data on a graphic and database data in a table. I don't know how to distinguish them. I use socket.io and mysql.

Server

socket.on('connection', function(client){
    console.log('Le client s\'est connecté au serveur');
    socketnavigateur = client; //socketnavigateur is a global variable for realtime data.
    
    var selectQuery = "SELECT * FROM Depassement";
        conn.query(selectQuery, function select(error, rows, fields){
            if(error){
                console.log(error);
                conn.end();
                return;
            }
   
            if(rows.length > 0){
                var Result = rows[0];
                client.send('id: '  + Result['Id_depassement']);
                client.send('Date : ' +  Result['Date_Dep']);
                client.send('Heure : '+ Result['Heure_Dep']);
                client.send('Puissance: ' + Result['P_reactive']);
            } else{
                console.log(error);
            }
        });
   
   
    //Message listener
    client.on('message', function(event){
        console.log('Réception du message du client =',event);
    });
   
    client.on('disconnect',function(){
        console.log('Le client s\'est déconnecté !');
    });
});

Client

var socket = io.connect();

        // connection listener
        socket.on('connect',function() {
            log('<span style="color:green;">Le serveur s\'est connecte au client !</span>');

        });
        // message listener
        socket.on('message',function(data) {
            log(data);
            console.log(data);
            drawGraph(data);
        });

        socket.on('disconnect',function() {
            log('<span style="color:red;">Le client s\'est déconnecte !</span>');
        });

        // function to display on client
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
            document.getElementById('id').innerHTML = message;
}

Thanks for your help and sorry if my english is bad :p



via M. Dupont

No comments:

Post a Comment