Building a Real-Time Chat Application with WebSockets πŸš€

Building a Real-Time Chat Application with WebSockets πŸš€

Welcome to the exciting world of real-time communication! In this blog, we'll walk you through the process of developing a simple chat application with WebSockets. Our goal is to understand how we can implement a basic chat application using a web socket connection(you can refer to: The previous blog on web socket). WebSockets allow us to establish persistent connections between clients and servers, allowing for immediate data transmission and engaging user experiences. In this article, we'll use Socket.io, a popular WebSocket library, to create our chat application.

Prerequisites πŸ› οΈ

Before we dive in, ensure you have the following:

  1. Basic knowledge of HTML, CSS, and JavaScript.

  2. Node.js installed on your system.

Setting Up the Project Structure πŸ—οΈ

First, let’s organize our project files:

markdownCopy code- chat-app/
  - public/
    - index.html
    - styles.css
    - app.js
  - server.js
  - package.json

In the public folder, we have our HTML (index.html), CSS (styles.css), and client-side JavaScript (app.js) files. The server-side code will be in server.js.

Creating the Frontend: HTML, CSS, and JavaScript πŸ–₯️

Our HTML file (index.html) contains the structure of our chat application. It provides a text input for messages and a button to send messages. The CSS file (styles.css) styles the chat interface. Here's the provided HTML and CSS code.

index.html:

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <!-- meta tags and title -->
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <h1 class="heading">Chatting</h1>
    <main>
        <div id="messages"></div>
        <section class="input-area">
            <input type="text" placeholder="Enter message" id="msgInput" />
            <button id="sendBtn">Send</button>
        </section>
    </main>

    <!-- Socket.io library -->
    <script src="/socket.io/socket.io.js"></script>
    <!-- Client-side JavaScript -->
    <script defer src="./app.js"></script>
</body>
</html>

styles.css:


:root {
  background-color: rgb(243, 237, 237);
  font-family: sans-serif;
}

body {
  padding: 0;
  margin: 0 auto;
  box-sizing: border-box;
  position: relative;
  height: 100vh;
  width: 100vw;
}

.heading {
  text-align: center;
  color: #444;
}

#messages {
  display: flex;
  flex-direction: column;
  gap: 8px;
  /* Set the messages container to grow and shrink as needed */
  flex: 1;
  overflow-y: auto; /* Add vertical scroll when messages overflow */
}

.message {
  margin: 2px 1rem;
  display: inline;
  background-color: rgb(215, 210, 204);
  border-radius: 1rem;
  padding: 0.4rem 1rem;
}
#messages > li:nth-child(odd) {
  background: #efefef;
}

.input-area {
  width: 100vw;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  gap: 0.2rem;
  position: fixed;
  bottom: 0;
  background-color: white; /* Set a background color for the input area */
  box-shadow: 0px -1px 5px 0px rgba(0, 0, 0, 0.2);
  padding: 4px 2px;
}

input {
  padding: 0.8rem 1.6rem;
  width: 80%;
  border-radius: 0.5rem;
}

button {
  padding: 0.8rem 1.6rem;
  border-radius: 0.8rem;
  border: 1px solid black;
  background-color: aliceblue;
  font-weight: 500;
  font-size: 1rem;
}

button:hover,
:active {
  cursor: pointer;
  background-color: rgb(193, 221, 246);
}

The client-side JavaScript (app.js) establishes a connection with the server using Socket.io and handles message sending and receiving.

Setting Up the Backend: Server Configuration πŸ› οΈ

Now, let's set up the server (server.js) using Node.js and Express. We will use Socket.io to handle WebSocket connections.

server.js:

import express from "express";
import http from "http";
import path from "path";
import { Server } from "socket.io";

const app = express();
const server = http.createServer(app);
const io = new Server(server);

// Socket.io
io.on("connection", (socket) => {
    console.log("A new user has been connected");

    // Listening for user messages
    socket.on('user-message', (message) => {
        console.log("A new user message:", message);
        io.emit("message", message); // Broadcast the message to all clients including the sender
    });
});

// Serve static files from the public directory
app.use(express.static(path.resolve(__dirname, "./public")));

// Serve the homepage
app.get("/", (req, res) => {
    return res.sendFile(path.resolve(__dirname, "./public/index.html"));
});

// Start the server on port 9000
server.listen(9000, () => console.log("Server is live at 9000"));

Running the Application πŸš€

  1. Install Dependencies: Navigate to your project folder in the terminal and run npm install to install the necessary packages (express and socket.io).

  2. Start the Server: Run node server.js to start the server. This will listen on port 9000.

  3. Open in Browser: Open your browser and navigate to http://localhost:9000 to see your chat application in action! πŸŽ‰

And here is a demo of how it will look:

And wohoo...!!! We have a real-time chatting application completed!! πŸ₯³

Β