When we Create Client Server Application,
Some time we Need To Check out Live Connectivity between Client & Server.
Let's we Understand by Example,
Server Code.
const fs = require('fs');
const http = require('http');
const path = require('path');
const SocketIOServer = require('socket.io');
const app = new http.Server();
app.on('request', (req, res) => {
const index = path.join(__dirname, 'public', 'index.html')
fs.readFile(index, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
});
app.listen(3000, 'localhost');
const io = new SocketIOServer(app);
// could also use "connection"
io.on('connect', function (socket) {
console.log(`${socket.id} "connect"`);
socket.on('ping', (data) => {
console.log('Receive "Ping Form Client"');
io.emit('pong', {});
console.log('Send "Pong To Client"');
});
socket.on('disconnect', () => {
console.log(`${socket.id} "disconnect"`);
});
});
When Server Recive Ping event , then he send Cilent Pong Event.
Client Side Code.
<!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">
<title>Socket.IO Events</title>
</head>
<body>
<h1>Socket.IO Events</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('pong', (data) => {
console.log('Receive "pong Form Server"');
});
socket.emit('ping', {});
console.log('Send "ping To Client"');
</script>
</body>
</html>
Here, Client Send Ping Event To Server. and server Replay With Pong Methods.
Just Copy & Past Above code for Test Ping Pong.
Thanks.
NodeJs Tutorial
Good work, Very Helpful code , thanks
ReplyDeleteThe Best of the Blogs You have Mentioned here.
ReplyDeleteMern stack online training
Mern stack training in hyderabad
Online Business Analyst Course
ReplyDeleteDevelop skills in requirements elicitation, stakeholder analysis, process modeling (BPMN/UML), and documentation (BRDs, FRDs, RTMs). Build a job-ready portfolio with real-time projects and get expert interview guidance for a successful BA career.