How to emit an event when a checkbox is clicked using Socket.IO? - GeeksforGeeks

15 Dec, 2021
Problem Statement: Task is to perform an action by emitting an event from the backend whenever a particular checkbox is clicked in the frontend. This needs to be done using Socket.IO and Node.js
Prerequisite:
Node.js : It is an open-source JavaScript Back-End technology.Express.js : It is a node.js server framework.Socket.io : It helps us to create a real-time bi-direction event-based communication between the server and the client.
Node.js : It is an open-source JavaScript Back-End technology.
Express.js : It is a node.js server framework.
Socket.io : It helps us to create a real-time bi-direction event-based communication between the server and the client.
Now we need to install the required packages for our project.
Installing the modules.npm install express socket.io
Installing the modules.
npm install express socket.io
Project structure:
Step 1: Create a server file named server.js.
server.js
// Importing express moduleconst express = require('express'); const app = express();       // Calling the public folderapp.use(express.static("public"));     // Handling get requestapp.get("/" , (req,res)=>{  res.send("GeeksforGeeks); });    // Listing the server app.listen(4000 , ()=>{    console.log("Server running on port 4000");)
Output: Now, If you open the local host i.e. localhost:4000 You will see the output i.e. — GeeksforGeeks.
Step 2: Now, Lets implement the socket into our server file i.e. server.js
Syntax:
const io = require('socket.io')(server);
server.js
// Importing express moduleconst express = require('express');const app = express();const server = require('http').Server(app);const io = require('socket.io')(server);  // Calling the public folderapp.use(express.static('public'))  // Handling get requestapp.get("/" , (req,res)=>{    res.render("index");});    // Listening to the serverserver.listen(4000 , ()=>{    console.log("server is running");})
Step 3: Now let’s create a basic Html file i.e. index.html and a JavaScript file i.e. index.js into our public folder.
Step 4 : Now let’s add socket.io into our front-end. Add this script into your html file.
<script src="socket.io/socket.io.js" defer></script>
Step 5 : Now let’s create check box functionality. In this we have created a simple check box, When we check the checkbox it will emit one socket event which listens by the server and then the server emits an acknowledged event which will be listened to by the client-side and after receiving that event it will alert the acknowledgment.
index.html
<!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">    <script src="socket.io/socket.io.js" defer></script>    <script src="index.js" defer></script></head><body>    <center>    <h1>GeeksforGeeks</h1>    <p><input id="check" type="checkbox"               onchange="changed()"/>        Click me    </p>      </center></body></html>
index.js
// Socket Initializedconst socket = io('/');  function changed(){   // Getting current state of checkbox.   var a = document.getElementById('check').checked;   if(a)   {         // Emiting the event.      socket.emit("checkedTrue");      }}  //Listening on the event.socket.on("acknowledged" , ()=>{    alert("Action acknowledged by the server");});
server.js
// Importing express moduleconst express = require('express');const app = express();const server = require('http').Server(app);const io = require('socket.io')(server);  // Calling the public folderapp.use(express.static('public'))  // Handling get requestapp.get("/" , (req,res)=>{    res.render("index");});  // Socketio.on("connection" , (socket)=>{    socket.on("checkedTrue" , ()=>{        socket.emit("acknowledged")    })})  // Listening the serverserver.listen(4000 , ()=>{    console.log("server is running");})
Output:
sweetyty
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript