Author: saqibkhan

  • Chat Application

    Prerequisites

    Make sure you have Python and Flask installed. You can install Flask using pip:

    pip install Flask Flask-SocketIO
    

    Project Structure

    Create a directory for your project and set it up like this:

    chat_app/
    ├── app.py
    ├── templates/
    │   └── index.html
    └── static/
    
    └── script.js

    Step 1: Backend (app.py)

    Create app.py for the Flask server:

    from flask import Flask, render_template
    from flask_socketio import SocketIO, emit
    
    app = Flask(__name__)
    socketio = SocketIO(app)
    
    @app.route('/')
    def index():
    
    return render_template('index.html')
    @socketio.on('message') def handle_message(msg):
    print('Received message: ' + msg)
    emit('message', msg, broadcast=True)
    if __name__ == '__main__':
    socketio.run(app, debug=True)

    Step 2: Frontend (index.html)

    Create index.html in the templates folder:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Chat App&lt;/title>
    &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    &lt;style>
        body { font-family: Arial, sans-serif; }
        #messages { list-style-type: none; padding: 0; }
        #messages li { padding: 8px; margin: 5px 0; background: #f4f4f4; border-radius: 4px; }
        #message-input { width: 80%; }
        #send-button { width: 15%; }
    &lt;/style>
    </head> <body>
    &lt;h1>Chat Room&lt;/h1>
    &lt;ul id="messages">&lt;/ul>
    &lt;input id="message-input" autocomplete="off" placeholder="Type a message..." />
    &lt;button id="send-button">Send&lt;/button>
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js">&lt;/script>
    &lt;script src="static/script.js">&lt;/script>
    </body> </html>

    Step 3: Client-side JavaScript (script.js)

    Create script.js in the static folder:

    const socket = io();
    
    const messages = document.getElementById('messages');
    const input = document.getElementById('message-input');
    const button = document.getElementById('send-button');
    
    button.onclick = function() {
    
    const message = input.value;
    socket.emit('message', message);
    input.value = '';
    }; socket.on('message', function(msg) {
    const item = document.createElement('li');
    item.textContent = msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
    });

    Step 4: Run the Application

    Navigate to your project directory and run the application:

    python app.py
    

    Open your browser and go to http://localhost:5000. You can open multiple tabs or browsers to simulate different users.

  • Social Media Dashboard

    Basic Structure

    1. HTML: Create the structure of the dashboard.
    2. CSS: Style the dashboard to make it visually appealing.
    3. JavaScript: Add interactivity and dynamic data (simulated in this case).

    Step 1: HTML

    Create an index.html file:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Social Media Dashboard&lt;/title>
    &lt;link rel="stylesheet" href="styles.css">
    </head> <body>
    &lt;div class="container">
        &lt;header>
            &lt;h1>Social Media Dashboard&lt;/h1>
        &lt;/header>
        &lt;div class="stats">
            &lt;div class="stat-card">
                &lt;h2>Followers&lt;/h2>
                &lt;p id="followersCount">0&lt;/p>
            &lt;/div>
            &lt;div class="stat-card">
                &lt;h2>Likes&lt;/h2>
                &lt;p id="likesCount">0&lt;/p>
            &lt;/div>
            &lt;div class="stat-card">
                &lt;h2>Posts&lt;/h2>
                &lt;p id="postsCount">0&lt;/p>
            &lt;/div>
        &lt;/div>
        &lt;button id="updateButton">Update Stats&lt;/button>
    &lt;/div>
    &lt;script src="script.js">&lt;/script>
    </body> </html>

    Step 2: CSS

    Create a styles.css file:

    body {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    } header {
    text-align: center;
    margin-bottom: 20px;
    } .stats {
    display: flex;
    justify-content: space-between;
    } .stat-card {
    background: #e7e7e7;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    flex: 1;
    margin: 0 10px;
    } button {
    display: block;
    width: 100%;
    padding: 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-top: 20px;
    } button:hover {
    background-color: #0056b3;
    }

    Step 3: JavaScript

    Create a script.js file:

    document.getElementById('updateButton').addEventListener('click', updateStats);
    
    function updateStats() {
    
    const followersCount = Math.floor(Math.random() * 1000);
    const likesCount = Math.floor(Math.random() * 5000);
    const postsCount = Math.floor(Math.random() * 100);
    document.getElementById('followersCount').textContent = followersCount;
    document.getElementById('likesCount').textContent = likesCount;
    document.getElementById('postsCount').textContent = postsCount;
    }

    Running the Dashboard

    1. Save the files in the same directory.
    2. Open index.html in a web browser.
    3. Click the “Update Stats” button to see random statistics.

    Extending the Dashboard

    You can expand this basic dashboard by:

    • Integrating real APIs (like the Twitter API, Instagram Graph API, etc.) to fetch live data.
    • Adding charts using libraries like Chart.js for better visualization.
    • Implementing user authentication to personalize the dashboard for different users.
  • Task Manager

    Basic Task Manager in Python

    class Task:
    
    def __init__(self, title, description):
        self.title = title
        self.description = description
        self.completed = False
    def complete(self):
        self.completed = True
    def __str__(self):
        status = "✓" if self.completed else "✗"
        return f"&#91;{status}] {self.title}: {self.description}"
    class TaskManager:
    def __init__(self):
        self.tasks = &#91;]
    def add_task(self, title, description):
        task = Task(title, description)
        self.tasks.append(task)
        print(f"Task '{title}' added.")
    def list_tasks(self):
        if not self.tasks:
            print("No tasks available.")
        for i, task in enumerate(self.tasks, start=1):
            print(f"{i}. {task}")
    def complete_task(self, index):
        if 0 &lt;= index &lt; len(self.tasks):
            self.tasks&#91;index].complete()
            print(f"Task '{self.tasks&#91;index].title}' completed.")
        else:
            print("Invalid task index.")
    def delete_task(self, index):
        if 0 &lt;= index &lt; len(self.tasks):
            removed_task = self.tasks.pop(index)
            print(f"Task '{removed_task.title}' deleted.")
        else:
            print("Invalid task index.")
    def main():
    manager = TaskManager()
    while True:
        print("\nTask Manager")
        print("1. Add Task")
        print("2. List Tasks")
        print("3. Complete Task")
        print("4. Delete Task")
        print("5. Exit")
        choice = input("Choose an option: ")
        if choice == '1':
            title = input("Enter task title: ")
            description = input("Enter task description: ")
            manager.add_task(title, description)
        elif choice == '2':
            manager.list_tasks()
        elif choice == '3':
            index = int(input("Enter task index to complete: ")) - 1
            manager.complete_task(index)
        elif choice == '4':
            index = int(input("Enter task index to delete: ")) - 1
            manager.delete_task(index)
        elif choice == '5':
            print("Exiting Task Manager.")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    How to Use

    1. Add Task: Enter a title and description for the task.
    2. List Tasks: View all tasks with their completion status.
    3. Complete Task: Mark a task as completed by its index.
    4. Delete Task: Remove a task by its index.
    5. Exit: Quit the application.

    Running the Code

    1. Save the code in a file named task_manager.py.
    2. Run the script using Python:
    python task_manager.py
  • StageXL

    Setting Up

    1. Create a new Dart project:
    dart create -t console my_stagexl_project cd my_stagexl_project
    1. Add StageXL to your pubspec.yaml:
    dependencies: stagexl: ^3.0.0
    1. Run dart pub get to install the dependency.

    Basic Example

    Here’s a simple example of a StageXL application that displays a rectangle and handles a mouse click event.

    main.dart

    import 'dart:html';
    import 'package:stagexl/stagexl.dart';
    
    void main() {
      // Create a Stage and Render the Canvas
      var canvas = querySelector('#stage') as CanvasElement;
      var stage = Stage(canvas);
      var renderLoop = RenderLoop();
      renderLoop.addStage(stage);
    
      // Create a simple rectangle
      var rectangle = Shape()
    
    ..graphics.rect(100, 100, 200, 100)
    ..graphics.fillColor(Color.Blue);
    // Add the rectangle to the stage stage.addChild(rectangle); // Add mouse click event rectangle.onMouseClick.listen((event) {
    rectangle.graphics.clear();
    rectangle.graphics.fillColor(Color.Red);
    rectangle.graphics.rect(100, 100, 200, 100);
    rectangle.graphics.fill();
    }); // Start the render loop renderLoop.start(); }

    HTML Setup

    Make sure you have an HTML file to load your Dart application. Create index.html:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>StageXL Example</title>
      <script defer src="main.dart.js"></script>
      <style>
    
    canvas {
      background-color: #f0f0f0;
    }
    </style> </head> <body> <canvas id="stage" width="800" height="600"></canvas> </body> </html>

    Build and Run

    1. Build your Dart application:
    dart compile js main.dart -o main.dart.js
    1. Open index.html in your browser.

    Explanation

    • Stage: Represents the main area where you draw.
    • Shape: Used to create shapes (like rectangles) that you can draw on the stage.
    • RenderLoop: A loop that continuously renders the stage.
  • Shelf

    Step 1: Set Up HTML

    Create an index.html file:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Digital Bookshelf&lt;/title&gt;
    &lt;link rel="stylesheet" href="styles.css"&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;My Digital Bookshelf&lt;/h1&gt;
        &lt;form id="book-form"&gt;
            &lt;input type="text" id="book-title" placeholder="Book Title" required&gt;
            &lt;input type="text" id="book-author" placeholder="Author" required&gt;
            &lt;button type="submit"&gt;Add Book&lt;/button&gt;
        &lt;/form&gt;
        &lt;div id="shelf" class="shelf"&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    </body> </html>

    Step 2: Add Some Style

    Create a styles.css file:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    color: #333;
    } .container {
    width: 80%;
    max-width: 600px;
    margin: auto;
    padding: 20px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } form {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    } input {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    } button {
    padding: 10px;
    background-color: #5cb85c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    } button:hover {
    background-color: #4cae4c;
    } .shelf {
    display: flex;
    flex-wrap: wrap;
    } .book {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    margin: 5px;
    width: calc(33.333% - 10px);
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
    }

    Step 3: Add Functionality with JavaScript

    Create a script.js file:

    javascriptCopy codedocument.getElementById('book-form').addEventListener('submit', function (e) {
    
    e.preventDefault();
    
    const title = document.getElementById('book-title').value;
    const author = document.getElementById('book-author').value;
    addBookToShelf(title, author);
    // Clear the input fields
    document.getElementById('book-title').value = '';
    document.getElementById('book-author').value = '';
    }); function addBookToShelf(title, author) {
    const shelf = document.getElementById('shelf');
    const bookDiv = document.createElement('div');
    bookDiv.className = 'book';
    bookDiv.innerHTML = &amp;lt;strong&amp;gt;${title}&amp;lt;/strong&amp;gt;&amp;lt;br&amp;gt;&amp;lt;em&amp;gt;${author}&amp;lt;/em&amp;gt;;
    
    shelf.appendChild(bookDiv);
    }

    How It Works

    1. HTML: The form collects the book title and author.
    2. CSS: Basic styles for the layout and appearance of the bookshelf.
    3. JavaScript: When the form is submitted, the book title and author are added to the shelf, and the input fields are cleared.

    Running the Project

    1. Save all three files in the same directory.
    2. Open index.html in a web browser.
  • Routemaster

    Setup a Basic Express Server with Routing

    1. Install Express: Make sure you have Node.js installed. Then create a new directory for your project and install Express:
    mkdir my-routemaster cd my-routemaster npm init -y npm install express
    1. Create the Server: Create a file named server.js:
    const express = require('express'); const app = express(); const PORT = 3000; // Define routes app.get('/', (req, res) => { res.send('Welcome to the Routemaster!'); }); app.get('/about', (req, res) => { res.send('This is the about page.'); }); app.get('/contact', (req, res) => { res.send('This is the contact page.'); }); // Start the server app.listen(PORT, () => { console.log(Server is running on http://localhost:${PORT}); });
    1. Run the Server: Start your server by running:
    node server.js
    1. Access the Routes: Open your browser and go to:
      • http://localhost:3000/ for the home page
      • http://localhost:3000/about for the about page
      • http://localhost:3000/contact for the contact page
  • Moor

    Step 1: Add Dependencies

    First, add the required dependencies to your pubspec.yaml:

    dependencies:
      drift: ^2.4.0
      drift_flutter: ^2.4.0
      sqlite3_flutter_libs: ^0.5.0 # For SQLite support
    
    dev_dependencies:
      build_runner: ^2.3.0
      drift_dev: ^2.4.0
    

    Step 2: Create a Database Model

    Create a new Dart file for your database model, e.g., database.dart.

    import 'package:drift/drift.dart';
    import 'package:drift/native.dart';
    
    part 'database.g.dart'; // The part directive for code generation
    
    @DataClassName('Task') // The class that will represent a row
    class Tasks extends Table {
      IntColumn get id => integer().autoIncrement()(); // Auto-incrementing ID
      TextColumn get name => text().withLength(min: 1, max: 50)(); // Task name
      BoolColumn get isComplete => boolean().withDefault(Constant(false))(); // Completion status
    }
    
    @DriftDatabase(tables: [Tasks])
    class AppDatabase extends _$AppDatabase {
      AppDatabase() : super(NativeDatabase.memory()); // Use in-memory database for testing
    
      @override
      int get schemaVersion => 1;
    
      // Define methods for database operations
      Future<List<Task>> getAllTasks() => select(tasks).get();
      Future insertTask(Insertable<Task> task) => into(tasks).insert(task);
      Future updateTask(Insertable<Task> task) => update(tasks).replace(task);
      Future deleteTask(Insertable<Task> task) => delete(tasks).delete(task);
    }
    

    Step 3: Generate the Code

    Run the following command to generate the necessary code:

    flutter pub run build_runner build
    

    This will create a file named database.g.dart with the generated code.

    Step 4: Use the Database

    Now you can use the database in your Flutter app. Here’s a simple example of how to use it:

    import 'package:flutter/material.dart';
    import 'database.dart'; // Import your database model
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      home: TaskList(),
    );
    } } class TaskList extends StatefulWidget { @override _TaskListState createState() => _TaskListState(); } class _TaskListState extends State<TaskList> { late AppDatabase _database; @override void initState() {
    super.initState();
    _database = AppDatabase(); // Initialize the database
    } Future<void> _addTask(String name) async {
    final task = TasksCompanion(
      name: Value(name),
      isComplete: Value(false),
    );
    await _database.insertTask(task);
    setState(() {}); // Refresh the UI
    } Future<List<Task>> _fetchTasks() async {
    return await _database.getAllTasks();
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Tasks')),
      body: FutureBuilder&lt;List&lt;Task>>(
        future: _fetchTasks(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }
          final tasks = snapshot.data ?? &#91;];
          return ListView.builder(
            itemCount: tasks.length,
            itemBuilder: (context, index) {
              final task = tasks&#91;index];
              return ListTile(
                title: Text(task.name),
                trailing: Checkbox(
                  value: task.isComplete,
                  onChanged: (value) {
                    // Update task completion status
                    final updatedTask = task.copyWith(isComplete: value);
                    _database.updateTask(updatedTask);
                    setState(() {}); // Refresh the UI
                  },
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Add a new task (for example)
          _addTask('New Task');
        },
        child: Icon(Icons.add),
      ),
    );
    } }

    Step 5: Run the App

    Run your Flutter app, and you should see a simple task list that allows you to add and check off tasks!

  • Task Management App

    Step 1: Set Up Your Project

    1. Create a new folder for your project, e.g., task-manager.
    2. Inside this folder, create three files:
      • index.html
      • styles.css
      • script.js

    Step 2: HTML Structure (index.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="styles.css">
    &lt;title>Task Manager&lt;/title>
    </head> <body>
    &lt;div class="container">
        &lt;h1>Task Manager&lt;/h1>
        &lt;input type="text" id="taskInput" placeholder="Add a new task...">
        &lt;button id="addTaskButton">Add Task&lt;/button>
        &lt;ul id="taskList">&lt;/ul>
    &lt;/div>
    &lt;script src="script.js">&lt;/script>
    </body> </html>

    Step 3: Add Some Styles (styles.css)

    body {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } input[type="text"] {
    width: 70%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    } button {
    padding: 10px;
    border: none;
    border-radius: 4px;
    background-color: #28a745;
    color: white;
    cursor: pointer;
    } button:hover {
    background-color: #218838;
    } ul {
    list-style-type: none;
    padding: 0;
    } li {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    } li button {
    background-color: #dc3545;
    }

    Step 4: Implement Functionality (script.js)

    document.getElementById('addTaskButton').addEventListener('click', addTask);
    
    function addTask() {
    
    const taskInput = document.getElementById('taskInput');
    const taskValue = taskInput.value.trim();
    if (taskValue) {
        const taskList = document.getElementById('taskList');
        // Create list item
        const li = document.createElement('li');
        li.textContent = taskValue;
        // Create delete button
        const deleteButton = document.createElement('button');
        deleteButton.textContent = 'Delete';
        deleteButton.addEventListener('click', () => {
            taskList.removeChild(li);
        });
        li.appendChild(deleteButton);
        taskList.appendChild(li);
        // Clear input
        taskInput.value = '';
    }
    }

    Step 5: Run Your App

    1. Open index.html in your web browser.
    2. You can now add tasks and delete them as needed.
  • Fitness Tracker

    Requirements

    1. Python: Make sure you have Python installed (version 3.6 or above).
    2. Libraries: Install the following libraries using pip:bashCopy codepip install matplotlib numpy

    Step 1: Set Up the Data Structure

    We’ll use a simple dictionary to store the fitness data.

    import random
    import time
    
    fitness_data = {
    
    "steps": 0,
    "heart_rate": 0,
    "calories_burned": 0
    }

    Step 2: Simulate Fitness Tracking

    We’ll create functions to simulate updating steps, heart rate, and calories burned.

    def update_steps():
    
    # Simulate step counting
    steps = random.randint(0, 100)
    fitness_data&#91;"steps"] += steps
    return steps
    def update_heart_rate():
    # Simulate heart rate measurement
    heart_rate = random.randint(60, 100)
    fitness_data&#91;"heart_rate"] = heart_rate
    return heart_rate
    def update_calories_burned(steps):
    # Simple formula for calories burned (approx.)
    calories = steps * 0.04
    fitness_data&#91;"calories_burned"] += calories
    return calories

    Step 3: Main Loop to Collect Data

    Now we’ll create a loop to collect data at regular intervals.

    def collect_data(duration=10):
    
    start_time = time.time()
    while (time.time() - start_time) &lt; duration:
        steps = update_steps()
        heart_rate = update_heart_rate()
        calories = update_calories_burned(steps)
        
        print(f"Steps: {fitness_data&#91;'steps']}, Heart Rate: {heart_rate} bpm, Calories Burned: {fitness_data&#91;'calories_burned']:.2f}")
        
        time.sleep(1)  # Collect data every second

    Step 4: Visualizing the Data

    To visualize the data, we can create a simple graph using matplotlib.

    import matplotlib.pyplot as plt
    
    def plot_data():
    
    # Data for plotting
    steps = &#91;]
    heart_rates = &#91;]
    calories = &#91;]
    for _ in range(10):
        steps.append(fitness_data&#91;"steps"])
        heart_rates.append(fitness_data&#91;"heart_rate"])
        calories.append(fitness_data&#91;"calories_burned"])
        time.sleep(1)  # Simulate time passing
    # Plotting
    plt.figure(figsize=(10, 5))
    
    plt.subplot(1, 3, 1)
    plt.plot(steps, label='Steps', color='blue')
    plt.title('Steps Over Time')
    plt.xlabel('Time (s)')
    plt.ylabel('Steps')
    
    plt.subplot(1, 3, 2)
    plt.plot(heart_rates, label='Heart Rate', color='red')
    plt.title('Heart Rate Over Time')
    plt.xlabel('Time (s)')
    plt.ylabel('Heart Rate (bpm)')
    
    plt.subplot(1, 3, 3)
    plt.plot(calories, label='Calories Burned', color='green')
    plt.title('Calories Burned Over Time')
    plt.xlabel('Time (s)')
    plt.ylabel('Calories')
    plt.tight_layout()
    plt.show()

    Step 5: Putting It All Together

    Finally, we’ll run the data collection and plotting functions.

    if __name__ == "__main__":
    
    collect_data(duration=10)  # Collect data for 10 seconds
    plot_data()  # Plot the collected data

    Running the Tracker

    1. Save your script as fitness_tracker.py.
    2. Run it using:bashCopy codepython fitness_tracker.py

    This will simulate tracking fitness data and visualize the results after collecting data for 10 seconds.

  • Prerequisites

    • Python installed on your machine
    • Basic understanding of Python and JavaScript
    • Flask and Flask-SocketIO libraries

    Step 1: Set Up the Environment

    1. Install Flask and Flask-SocketIO:Open your terminal and run:
    pip install Flask Flask-SocketIO
    1. Create a Project Directory:bashCopy codemkdir chat_app cd chat_app
    2. Create the main application file:Create a file named app.py.

    Step 2: Build the Backend

    Open app.py and add the following code:

    from flask import Flask, render_template
    from flask_socketio import SocketIO, emit
    
    app = Flask(__name__)
    socketio = SocketIO(app)
    
    @app.route('/')
    def index():
    
    return render_template('index.html')
    @socketio.on('message') def handle_message(msg):
    print('Message received: ' + msg)
    emit('message', msg, broadcast=True)
    if __name__ == '__main__':
    socketio.run(app)

    Step 3: Create the Frontend

    1. Create a templates folder in your project directory.
    mkdir templates
    1. Create an index.html file inside the templates folder:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Chat Application&lt;/title>
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.min.js">&lt;/script>
    &lt;style>
        body { font-family: Arial, sans-serif; }
        #messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; margin-bottom: 10px; }
        #message-input { width: 80%; }
    &lt;/style>
    </head> <body> <h1>Chat Application</h1> <div id="messages"></div> <input id="message-input" placeholder="Type your message here..."> <button id="send-button">Send</button> <script>
    const socket = io();
    socket.on('message', function(msg) {
        const messagesDiv = document.getElementById('messages');
        messagesDiv.innerHTML += '&lt;div>' + msg + '&lt;/div>';
        messagesDiv.scrollTop = messagesDiv.scrollHeight; // Auto-scroll
    });
    document.getElementById('send-button').onclick = function() {
        const input = document.getElementById('message-input');
        const msg = input.value;
        socket.emit('message', msg);
        input.value = ''; // Clear input
    };
    </script> </body> </html>

    Step 4: Run Your Application

    Go back to your terminal and run:

    python app.py
    

    Your chat application will start on http://localhost:5000. Open this URL in multiple tabs or different browsers to test the chat functionality.

    Step 5: Enhance Your Application (Optional)

    • Usernames: Allow users to set a username.
    • Timestamps: Add timestamps to messages.
    • Message History: Store messages on the server for a richer chat experience.
    • Styling: Use CSS frameworks like Bootstrap for a better look.