Javascript Dgram to Webpage

i know i am missing something simple but i need to have My console output be displayed in a webpage with express and ejs can anyone help me out, First snippet is the Console output second snippet is the Attemp to goto a webpage, i have a counter and timer putting data to a page, any help would be great.



import express from "express";
import dgram from "dgram";

const socketServer = dgram.createSocket("udp4");
const app = express();

app.get("/", (req, res) => {
  //res.send("Hello World!");
});

socketServer.on("message", (msg, rinfo) => {
  console.log(`got messsage from ${rinfo.address}, data: ${msg}`);
});

app.listen(5000, () => {
  socketServer.bind(5000);
  console.log(`Backend started!`);
});


Attempt:2

const express = require('express')
const dgram = require('dgram')
const app = express()
const port = 3000
const socketServer = dgram.createSocket("udp4");
app.use('/', express.static('public'));

var data = "Update";
var number = 1;
   // server Sent Events 
app.get('/server-sent-events', function(req, res) {

    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });

    var interval = setInterval(function(){
        data = " "+number;
       // console.log("SENT: "+msg);
        //console.log(`got messsage from ${rinfo.address}, data: ${msg}`);
        res.write("data: " + data + "\n\n")
        //socketServer.on("message", (msg, rinfo) => {
        //console.log(`got messsage from ${rinfo.address}, data: ${msg}`);
        //  res.write("UDP: " + ${msg} + "\n\n")

        number++;
        // Increment Values on webpage  
    }, randomInteger(2,9)*900);

    // close
    res.on('close', () => {
        clearInterval(interval);
        res.end();
    });
})

function randomInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}  

app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`)
})

I don’t have a full understanding of your project here, and only a reasonably basic grasp of nodejs.

The following seems to be a pretty good starter guide to using ejs, render and how to pass data to ejs templates.

As for the timer. There is probably a more elegant way, but once ejs has rendered the html, my approach would be to update the counter with vanilla js. For instance using textContent on a specific dom node.

In fact in the past I have just included something like <script src='.js/timer.js'></script> in my rendered HTML which will import the vanilla js to do that.

As I say there is probably a better pattern for this, and maybe someone else can steer you in the right direction.

1 Like

Hi @syscorenx, if I understand your problem correctly, you’d need need to listen for messages inside the route handler for the given amount of time:

app.get('/server-sent-events', function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive'
  })

  function writeMessage (msg, rinfo) {
    res.write(`UDP: ${msg}\n`)
  }

  // Start listening for messages
  socketServer.on('message', writeMessage)

  setTimeout(() => {
    // Stop listening when ending the response
    socketServer.off('message', writeMessage)
    res.end()
  }, randomInteger(2, 9) * 900)
})

And then somewhere else, just send() a message like so (no need to bind() to an address):

const dgram = require('dgram')
const socketServer = dgram.createSocket('udp4')

socketServer.send('hello', 5000, 'localhost', err => {
  console.log(err)
  socketServer.close()
})

HTH

1 Like