Javascript Dgram to Webpage – JavaScript – SitePoint Forums

I know I’m missing something simple, but I need my console output to be displayed in a webpage with express and ejs. and timer putting data on 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 + "nn")
        //socketServer.on("message", (msg, rinfo) => {
        //console.log(`got messsage from ${rinfo.address}, data: ${msg}`);
        //  res.write("UDP: " + ${msg} + "nn")

        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 understanding of nodejs.

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

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

In fact, in the past I’ve just included something like in my HTML renderer which will import the vanilla js to do it.

Like I said, there’s probably a better model for this, and maybe someone else can point you in the right direction.



1 like

Hi @syscorenx, if I understand your problem correctly, you need to listen for messages inside the route handler for the timeout:

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 elsewhere, just send() a message like this (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

Source link

About Irene S. Stroupe

Check Also

Does anyone know RedbeanPHP? – PHP – SitePoint Forums

I’m using RedbeanPHP ORM to design a personal text-based web game. So what I’m trying …