DEV Community

sadiul hakim
sadiul hakim

Posted on

5

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!❤

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs