How to emit an event when a checkbox is clicked using Socket.IO?
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
- 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
Step 1: Create a server file named server.js.
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
const io = require('socket.io')(server);
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.