[英]Send data to Node.js Clients
I am trying to build a Node.js App to Monitor some Raspberry Pi's. 我正在尝试构建一个Node.js应用程序来监视一些Raspberry Pi。
Since those Raspberries don't have a static IP, they send an UDP Broadcast every 5 seconds. 由于这些树莓没有静态IP,因此它们每5秒发送一次UDP广播。
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. 我可以使用Node.js捕获广播,但无法触发新功能来通知Node.js客户端。
I tried WebSockets
, ServerSendEvents
and Socket.io
. 我尝试了
WebSockets
, ServerSendEvents
和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: Node.js应用程序:
// ============================================================================================================== // ===== 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.
我不想发回UDP消息。 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.
此UDP广播应触发(Node.js)事件,该事件应更新html并将树莓派pi(向其发送UDP程序包)显示为在线。
EDIT: 编辑:
In documentation from official page of nodejs ( DOCUMENTATION ): 在来自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. “如果消息是被推入缓冲区的对象”-假设某个RPI已打开并开始发送UDP消息,该消息应传递给服务器什么,以便服务器可以将其传递给显示:mac地址,仅因为它发送了一些消息可以确定它是否打开,如果它不这样发送简单的话。 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.
还要显示客户端上的更改,您应该在服务器上初始化TCP套接字以将信息传递到服务器网页,以使用jquery更新html上的内容。
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). 现在这里是HTML Java脚本部分(我亲自制作了main.js文件,并将所有Java脚本写入其中,并使用将其作为src导入到html中)。 Using jquery in main.js:
在main.js中使用jquery:
$(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: 如果您在html中放置文本标签以显示特定的rpi是向上还是向下,则这部分代码在此方案中有效:
Multiple RPI + Server - RPI sends UDP data with mac to server. 多个RPI +服务器-RPI通过mac将UDP数据发送到服务器。 Server device is used to receive data and show it on any device as web page and change data if RPI is UP/DOWN.
服务器设备用于接收数据并将其作为网页显示在任何设备上,如果RPI为UP / DOWN,则更改数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.