简体   繁体   中英

Send data to Node.js Clients

I am trying to build a Node.js App to Monitor some Raspberry Pi's.

Since those Raspberries don't have a static IP, they send an UDP Broadcast every 5 seconds.

I'm able to catch that Broadcast with Node.js , but I'm failing to trigger a new function to notify the Node.js Clients.

I tried WebSockets , ServerSendEvents and Socket.io .

I'm able to use Example Code and they work just fine.

But I'm not Experienced enough to build a function which will send data to the clients.

Node.js App:

 // ============================================================================================================== // ===== Dependencies =========================================================================================== // ============================================================================================================== var dgram = require('dgram'); var http = require('http'); var url = require("url"); var path = require("path"); var fs = require("fs"); // ============================================================================================================== // ===== HTTP Serv ============================================================================================== // ============================================================================================================== var server = http.createServer(function(request, response) { var uri = url.parse(request.url).pathname, filename = path.join(process.cwd(), uri); var contentTypesByExtension = { '.html': "text/html", '.css': "text/css", '.js': "text/javascript", '.svg': "image/svg+xml" }; fs.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\\n"); response.end(); return; } if (fs.statSync(filename).isDirectory()) filename += '/index.html'; fs.readFile(filename, "binary", function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\\n"); response.end(); return; } var headers = {}; var contentType = contentTypesByExtension[path.extname(filename)]; if (contentType) headers["Content-Type"] = contentType; response.writeHead(200, headers); response.write(file, "binary"); response.end(); }); }); }); // ============================================================================================================== // ===== HeartBeat Broadcast ==================================================================================== // ============================================================================================================== var bcast = dgram.createSocket('udp4'); bcast.on('message', function (message) { console.log("Triggered: UDP Broadcast"); // If UDP Broadcast is received, send message/data to client. }); bcast.bind(5452, "0.0.0.0"); // ============================================================================================================== // ===== Start Server =========================================================================================== // ============================================================================================================== server.listen(80); console.log("Static file server running/\\nCTRL + C to shutdown"); 

EDIT: I think I did not explain myself accurate enough. I do not want to send a UDP message back. This UDP Broadcast should fire an (Node.js) event, which should update the html and display the raspberry pi (whom send the UDP Package) as online.

EDIT:

In documentation from official page of nodejs ( DOCUMENTATION ):

var socket = require('socket.io')(http);

var bcast = dgram.createSocket('udp4');
bcast.bind(5452, "0.0.0.0");
bcast.on('message', function (message, remote) {
    ////if message is an Object pushed into Buffer////
    message = message.toString('utf8');
    socket.emit("HTML_Update", message);

//////////////////////////////////Solution for unedited question//////////////////////////
//   var msgBuffer = Buffer.from(message.toString(); //creating a buffer                //
//   bcast.send(msgBuffer, 0, msgBuffer.length, remote.port, remote.address, (err) => { //
//       bcast.close();                                                                 //
//   }); //sending message to remote.address:remote.port (like localhost:23456)         //
//                                                                                      //
//                  **build a function which will send data to the clients**            //      
//////////////////////////////////Solution for unedited question//////////////////////////
});

"If message is an Object pushed into Buffer" - lets say that one of the RPI turned on and started sending UDP message, what should the message pass to server so server can pass it to display: mac address only because if it sends something You can be sure its on, if it does not send its off simple as that. Also to show that change on client You should initialize TCP sockets on server to pass info to servers web page to update content on html with jquery.

Now here is the HTML java script part (I personally make main.js file and write all java script into it and use import it as src into html). Using jquery in main.js:

$(document).ready(function() {    
    var time = new Date();
    var rpi = { 
        "list" : ["mac1", "mac2", "mac3"], 
        "time" : [time.getTime(), time.getTime(), time.getTime()], 
        "label" : ["label_ID1", "label_ID2", "label_ID3"]};
    var socket = io.connect('http://your_server_address:80');

    setInterval( function(){
         for (var i = 0; i <= 2; i++){
             if((rpi.time[i] + 10000) < time.getTime()){
                 $(rpi.label[i]).text("RPI " + rpi.list[i] + " is DOWN");
             }
         }
    }, 5000);

    socket.on("HTML_Update", function(data){
        for (var i = 0; i<=2; i++) {
             if (data.toString().equals(rpi.list[i])) {
                 $(rpi.label[i]).text("RPI: "+ rpi.list[i] + " is UP");
                 rpi.time[i] = time.getTime();
             }
        }        
    });         
}

If You put text label in html to show if specific rpi is up or down this part of code works in this scheme:

Multiple RPI + Server - RPI sends UDP data with mac to server. Server device is used to receive data and show it on any device as web page and change data if RPI is UP/DOWN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM