Creating a Simple Chat Application

Loading

Creating a simple chat application requires both a frontend (for user interaction) and a backend (for handling messages). Here, we’ll build a basic real-time chat application using Flask (backend) and Socket.IO (real-time communication).


1️⃣ Install Required Libraries

Before starting, install the necessary Python packages:

pip install flask flask-socketio eventlet

flask → Web framework for Python.
flask-socketio → Enables real-time, bidirectional communication.
eventlet → Makes the server asynchronous.


2️⃣ Setting Up the Backend (Flask + Socket.IO)

Create a file app.py for the backend.

from flask import Flask, render_template
from flask_socketio import SocketIO, send

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")

@app.route("/")
def index():
return render_template("chat.html") # Frontend page

@socketio.on("message")
def handle_message(msg):
print(f"Message: {msg}")
send(msg, broadcast=True) # Send message to all clients

if __name__ == "__main__":
socketio.run(app, debug=True)

@socketio.on("message") → Listens for incoming messages.
send(msg, broadcast=True) → Broadcasts messages to all users.


3️⃣ Setting Up the Frontend (HTML + JavaScript)

Create a templates folder and inside it, a file chat.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat App</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
<h2>Simple Chat Application</h2>
<div id="chat-box"></div>
<input id="message" type="text" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>

<script>
var socket = io.connect("http://127.0.0.1:5000");

socket.on("message", function(msg) {
var chatBox = document.getElementById("chat-box");
chatBox.innerHTML += "<p>" + msg + "</p>";
});

function sendMessage() {
var message = document.getElementById("message").value;
socket.send(message);
document.getElementById("message").value = "";
}
</script>
</body>
</html>

socket.on("message", function(msg) {...} → Listens for new messages.
socket.send(message); → Sends the message to the server.


4️⃣ Running the Application

  1. Run the Python backend: bashCopyEditpython app.py
  2. Open http://127.0.0.1:5000/ in multiple browser tabs.
  3. Send messages, and see them appear in real-time.

5️⃣ Adding Usernames (Enhancement)

Modify the JavaScript in chat.html to ask for a username:

<script>
var username = prompt("Enter your name:");
var socket = io.connect("http://127.0.0.1:5000");

socket.on("message", function(msg) {
var chatBox = document.getElementById("chat-box");
chatBox.innerHTML += "<p>" + msg + "</p>";
});

function sendMessage() {
var message = document.getElementById("message").value;
socket.send(username + ": " + message);
document.getElementById("message").value = "";
}
</script>

✔ This will attach usernames to each message.


6️⃣ Deploying the Chat App

For deployment, use Gunicorn + Nginx (for production).
Install Gunicorn:

pip install gunicorn

Run the app with:

gunicorn -w 4 -k eventlet app:app

Leave a Reply

Your email address will not be published. Required fields are marked *