Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 21, 2021 10:09 pm GMT

Create a Real-Time digital clock with node and socket.io..

At first setup your nodejs project.Then install socket.io and express.
This is going to be our folder structure...

folder structure

In index.js our nodejs+socket.io+express code is going to be ...

import express from 'express';import http from 'http';import { Server } from 'socket.io';const app = express();const expressServer = http.createServer(app);app.use(express.json());app.use(express.static('public'));const io = new Server(expressServer);io.on('connect', function (socket) {    console.log('a user is connected');    setInterval(function () {        let date = new Date().toLocaleTimeString()        socket.send(date)    }, 1000)    socket.on('disconnect', () => {        console.log('user disconnected.')    })})app.get('/', (req, res, next) => {    res.render('index.html');})expressServer.listen(4000, () => {    console.log('server is listening.')})

and in index.html html code is going to be..

<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta http-equiv="X-UA-Compatible" content="IE=edge" />    <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <title>Socket</title>  </head>  <body>    <h1 id="time"></h1>  </body>  <script src="/socket.io/socket.io.js"></script>  <script>    let socket = io();    socket.on("message", function (msg) {      document.getElementById("time").innerHTML = "";      document.getElementById("time").innerHTML = msg;    });  </script></html>

Now use should see your rea-time running clock in browser..

clock

Thanks!


Original Link: https://dev.to/suhakim/create-a-real-time-digital-clock-with-node-and-socketio-53dm

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To