Changing the content of HTML body at runtime periodically - NodeJS

930 views Asked by At

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body></body>
</html>

app.js

I have a simple UDP Socket and a simple HTTP Server:

var socket = require( "dgram" ).createSocket( "udp4" );
socket.on("message", function ( message, requestInfo ) {
    document.body.innerHTML = message; // which obviously wrong
    // because the file is running on the client-side
    // I'm looking for something equivalent 
});

socket.bind(1247);

var http = require('http'), fs = require('fs');
fs.readFile('./index.html', function (err, html) {
   http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(1247,'xx.xx.xx.xx');
});

I am receiving the UDP messages successfully and periodically (every 5 seconds) from another device.

Is there a way to change the content of the HTML body after the first request from the user every time it receives the UDP message ?

1

There are 1 answers

0
luxdvie On BEST ANSWER

If you want fast communication between the server and client, and your server side processing is getting the messages on a socket, then I'd recommend using socket.io.

You can establish a web-socket connection between the client and server, and the server can send the message down to all clients when it receives the message. On your client, you'd have code similar to what you've already created. This is an example snippet from socket.io docs.

socket.on('new message', function (data) {
    document.body.innerHTML = data;
    // do something with the new data
});

This answer contains a good socket.io example.