I made a Nextjs app that shows the live random data generated by this api:
// pages/api/randomNumber.js
export default (req, res) => {
const randomNum = Math.floor(Math.random() * 100) + 1;
res.status(200).json({ number: randomNum });
};
In the pages/index.js
I have:
import Image from "next/image";
import { Inter } from "next/font/google";
import { useState, useEffect } from 'react';
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
const [randomNumber, setRandomNumber] = useState(null);
useEffect(() => {
const fetchData = async () => {
const res = await fetch('/api/randomNumber');
const data = await res.json();
setRandomNumber(data.number);
};
fetchData();
const interval = setInterval(fetchData, 1000);
return () => clearInterval(interval);
}, []);
return (
<main
className={`flex min-h-screen flex-col items-center justify-between p-24 ${inter.className}`}>
<p>{randomNumber}</p>
</main>
);
}
I also wrote a python script that generates random data and sends it over the network:
import socket
import random
import time
UDP_IP = "127.0.0.1" # Replace with the IP address of the Next.js app
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
number = random.randint(1, 100)
message = str(number).encode()
print(number)
sock.sendto(message, (UDP_IP, UDP_PORT))
time.sleep(1)
Now in the API of the Nextjs app, I want to replace the randomly generated data of the JS code by the one generated by the python code which is accessible over the network.
A NodeJS code like the one below log the data coming from the python script in the Terminal:
const dgram = require('dgram');
const UDP_IP = '127.0.0.1';
const UDP_PORT = 5005;
const sock = dgram.createSocket('udp4');
sock.bind(UDP_PORT, UDP_IP);
sock.on('message', (data, addr) => {
console.log(`${data}`);
});
console.log(`Listening on ${UDP_IP}:${UDP_PORT}`);
I want to know the Nextjs way of doing this.