Day 49: Building a Real-Time Chat Application with WebSocket | Harshil Chovatiya

Day 49: Building a Real-Time Chat Application with WebSocket | Harshil Chovatiya

Harshil Chovatiya - Day 49: Building a Real-Time Chat Application with WebSocket

Introduction:

Welcome to Day 49, where we'll delve into the exciting world of real-time applications by building a chat application using WebSocket. WebSocket provides a full-duplex communication channel over a single, long-lived connection, enabling real-time data exchange between clients and servers. In this project, you'll create a basic real-time chat application to enhance your understanding of WebSocket implementation.

Day 49: Building a Real-Time Chat Application with WebSocket | Harshil Chovatiya

Project Overview:

We'll build a simple chat application where users can join a chat room, send messages, and see real-time updates. This project emphasizes the integration of WebSocket for bidirectional communication, allowing messages to be instantly delivered to all connected clients.

Project Structure:

                  
                    project/
                  
                      │   
                      └── index.html
                      └── style.css
                      └── app.js
                      └── server.js
                  
                    

Detailed Steps:

1. HTML Structure (index.html):

                    
                  
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-Time Chat Application</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="chat-container">
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="Type your message...">
    <button onclick="sendMessage()">Send</button>
  </div>
  <script src="app.js"></script>
</body>
</html>
                  
                

2. Styling (styles.css):

                  

                  
body {
  font-family: 'Arial', sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

#chat-container {
  max-width: 600px;
  width: 100%;
  background-color: #fff;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

#messages {
  height: 200px;
  overflow-y: scroll;
  margin-bottom: 10px;
}

input {
  width: 70%;
  padding: 10px;
  margin-right: 10px;
}

button {
  padding: 10px;
  cursor: pointer;
}

                  
                

3. JavaScript Implementation (app.js):

                    
                    
const socket = new WebSocket('ws://localhost:3000');

socket.addEventListener('open', (event) => {
  console.log('Connected to WebSocket');
});

socket.addEventListener('message', (event) => {
  const messagesContainer = document.getElementById('messages');
  const messageElement = document.createElement('div');
  messageElement.textContent = event.data;
  messagesContainer.appendChild(messageElement);
  messagesContainer.scrollTop = messagesContainer.scrollHeight;
});

function sendMessage() {
  const messageInput = document.getElementById('messageInput');
  const message = messageInput.value.trim();
  if (message !== '') {
    socket.send(message);
    messageInput.value = '';
  }
}

                  
                

4. Server Implementation (server.js):

          
            
              const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    // Broadcast the message to all connected clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});

server.listen(3000, () => {
  console.log('Server is running on port 3000');
});

            
         

Usage:

  1. Run npm install express http ws to install the required Node.js packages.
  2. Start the server by running node server.js.
  3. Open index.html in multiple browser tabs or windows.
  4. Enter a username and start chatting in real-time!

Conclusion:

Congratulations on completing the real-time chat application with WebSocket! Through this project, you've gained valuable experience in implementing bidirectional communication, allowing users to engage in instant conversations. WebSocket's efficiency in providing a persistent connection for real-time updates has been highlighted in this application.

As you reflect on this journey, consider expanding the functionality of your chat application. You may explore features such as user authentication, private messaging, or even multimedia sharing. Additionally, optimizing the user interface and enhancing the overall user experience can further elevate the project.

Real-time applications are prevalent in various domains, from chat platforms to collaborative editing tools. The skills you've acquired in this project can be applied to a wide range of real-time scenarios. Keep exploring and experimenting with WebSocket and other technologies to stay at the forefront of web development.

Thank you for joining us on Day 49 of this coding adventure. Your dedication to learning and building is commendable. Happy coding, and may your future projects be filled with innovation and success!

Social Media

Comments