How to Configure Socket.IO with Demo-Chat App in Node.js?


Socket.io is a popular JavaScript library that allows us to communicate between the server and the client. We can create an instance of socket.io on the client and server sides and listen to or emit the events from both sides. Also, we can listen to the event emitted from the server on multiple web clients.

In real-time, we can use the socket.io library to create chat applications and online games requiring bi-direction communication. For example, if you have observed while playing chess or Ludo, it allows us to talk with our opponent.

In this tutorial, we will learn to configure the socket.io with a demo chat app in Node.js

Users should follow the steps below to create a chat application.

  • Step 1 − First, we require to create a node project. Users should execute the below command in the project directory.

npm init -y
  • Step 2 − After that, we require to install the dependencies in the node project by executing the below command in the project directory.

npm i express socket.io
  • Step 3 − Now, execute the below command to create empty files in the project.

touch app.js index.html

Users can now observe that app.js and index.html files are created in the project directory.

  • Step 4 − Next, we will create a server for the node application.

  • Step 4.1 − First, import the required dependencies, and initialize the application.

const app = express();
const { Server } = require("socket.io");
const server = http.createServer(app);
const io = new Server(server);
  • Step 4.2 − Configure the routes and send the index.html file.

app.get("/", (req, res) => {
   res.sendFile(__dirname + "/index.html");
});
  • Step 4.3 − Establish a connection with the client.

io.on("connection", (socket) => {
});
  • Step 4.4 − Whenever the ‘send name’ event is received on the server side, it emits it again from the server. So all connected clients can receive the event and message.

socket.on("send name", (username) => {
   io.emit("send name", username);
});
  • Step 4.5 − Write the same code to listen and emit the ‘send message’ event.

  • Step 4.6 − Write the code to run the node server.

server.listen(port, () => {
   console.log(`Server is listening at the port: ${port}`);
});
  • Step 5 − We have successfully set up the node server. Now, we require to set up the client.

  • Step 5.1 − In the index.html file, create inputs to take name and message input. Also, create a ‘send’ button. Furthermore, style the HTML elements to make them attractive.

  • Step 5.2 − In JavaSctipt, initialize the socket connection.

let socket = io();
  • Step 5.3 − Add the click event on the button. Whenever users click the button, access the name and message value, and emit the ‘’send name’ and ‘send message events.

socket.emit('send name', myName.value);
socket.emit('send message', myMessage.value);
  • Step 5.4 − Whenever we listen to the ‘send message’ or ‘send name’ event on the client side, get the message and append it to the web page.

Here, we have given full examples of codes.

Example

Filename – Index.html

Users should copy the below code and paste it into the index.html file of the project. In this file, we take the input value and emit the events using the name and message value. Also, we have added some styles to the div element while showing messages on the web page.

<!DOCTYPE html>
<html>
<head>
   <style>
      input {
         width: 300px;
         margin: 5px auto;
         padding: 10px;
         font-size: 20px;
         border: 3px solid blue;
         border-radius: 10px;
      }
      button {
         width: 100px;
         margin: 5px auto;
         padding: 10px;
         font-size: 20px;
         border: 3px solid blue;
         border-radius: 10px;
         background-color: aqua;
         margin: 0 auto;
      }
      .message {
         width: 100%;
         margin: 0 auto;
         display: flex;
         flex-direction: column;
         justify-content: center;
         align-items: center;
      }
   </style>
</head>
<body>
   <h2> Chat App using NodeJS and Socket.io </h2>
   <!-- creating the input div elements -->
   <div class = "message">
      <input type = "text" id = "name" placeholder = "your name">
      <br> <br>
      <input type = "text" id = "message" placeholder = "your message">
      <br> <br>
      <button id = "send"> Send </button>
   </div>
   <br> <br> <br>
   <div id="messageContent"> </div>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>

   // initialize the socket on client side
   let socket = io();
   
   // accessing the input elements
   let myName = document.getElementById("name");
   let myMessage = document.getElementById("message");
   let executeSend = document.getElementById("send");
   let messageContent = document.getElementById("messageContent");
   
   // adding the click event listener to the send button
   executeSend.addEventListener("click", (e) => {
      e.preventDefault();
      if (message.value) {
         // emit the events
         socket.emit('send name', myName.value);
         socket.emit('send message', myMessage.value);
         message.value = "";
      }
   });
   
   //Embedding the name in the div element
   socket.on("send name", (username) => {
      let senderName = document.createElement("div");
      senderName.style.width = "70%";
      senderName.style.color = "green";
      senderName.style.textAlign = "center";
      senderName.style.backgroundColor = "aqua";
      senderName.innerHTML = username + ":";
      senderName.style.margin = "5px auto";
      senderName.style.fontSize = "30px";
      messageContent.appendChild(senderName);
   });   
   
   // embedding the message in the div element
   socket.on("send message", (chat) => {
      let message = document.createElement("div");
      message.style.width = "70%";
      message.style.margin = "5px auto";
      message.style.fontSize = "20px";
      message.innerHTML = chat;
      messageContent.appendChild(message);
   });
</script>
</html>

Filename – App.js

Users should copy the below code and paste it into the app.js file. In this code, we set up the node server. Also, we have connected the server with the client using the socket.

// Import required libraries
const express = require("express");
const http = require("http");

// Initialize the app
const app = express();
const { Server } = require("socket.io");

// Create server using http
const server = http.createServer(app);
const io = new Server(server);

// send index.html file to the client
app.get("/", (req, res) => {
   res.sendFile(__dirname + "/index.html");
});

// Listen for the connection event with the client
io.on("connection", (socket) => {
   socket.on("send name", (username) => {
      io.emit("send name", username);
   });

   socket.on("send message", (chat) => {
      io.emit("send message", chat);
   });
});

// run the server on port 3000
const port = 3000;
server.listen(port, () => {
   console.log(`Server is listening at the port: ${port}`);
});

Users can execute the below command in the terminal to run the node server.

node app.js

Users can open the http://localhost:3000/ URL in two different tabs and send messages from one tab. They can observe that the second tab will also receive the message as it works as a different client.

Now, let’s understand the flow of the application. So, whenever we open the http://localhost:3000/ URL in the browser, it shows an index.html file. When we click the send button after entering the input value, it emits the ‘send name’ and ‘send message’ events from one client with the value of message and name. After that, the server receives the event and again emits the same events to send the message and name to all connected clients.

Next, we receive the event on every client and show the message on the web page. So, we require to send a message to the server first to send a message to all clients.

Updated on: 04-May-2023

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements