This content originally appeared on DEV Community and was authored by sadiul hakim
At first setup your nodejs project.Then install socket.io and express.
This is going to be our 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..
Thanks!❤
This content originally appeared on DEV Community and was authored by sadiul hakim
sadiul hakim | Sciencx (2021-12-21T22:09:39+00:00) Create a Real-Time digital clock with node and socket.io... Retrieved from https://www.scien.cx/2021/12/21/create-a-real-time-digital-clock-with-node-and-socket-io/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.

