DEV Community

sadiul hakim
sadiul hakim

Posted on

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.')
})
Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

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

clock

Thanks!❤

Discussion (0)