This project implements a web-based chat application where users can connect, set their usernames, and exchange messages in real-time. The application utilizes Flask, a Python web framework, for server-side logic and routing, and SocketIO for bi-directional communication between the server and clients.
Key Features:
- User Authentication: Users are assigned a unique device ID stored in cookies, ensuring a personalized experience without requiring traditional user accounts.
- Username Assignment: Upon connection, users are prompted to set a username, which is then stored along with a randomly generated color for identification.
- Real-Time Messaging: Users can send messages instantly to the server, which broadcasts them to all connected clients. Each message includes the sender’s username and a distinctive color.
- Persistence: Usernames and their associated colors are saved and loaded from a JSON file (
user_names.json), ensuring persistence across server restarts. - Security: The application uses SSL/TLS encryption to secure communication, enhancing confidentiality and integrity of data transmission.
Technologies Used:
- Flask: Provides the web application framework and handles HTTP requests and responses.
- SocketIO: Facilitates real-time, bidirectional communication between the web clients and server.
- JavaScript (with jQuery): Handles dynamic client-side interactions, such as sending/receiving messages and updating the chat interface.
- HTML/CSS: Structures the user interface and styles the components for a cohesive chat experience.

iPhone

Laptop
Python Server
from flask import Flask, render_template, request, jsonify, make_response
from flask_socketio import SocketIO, emit
import os
import json
from uuid import uuid4
import random
import ssl
# Initialize Flask application
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!' # Secret key for session management
socketio = SocketIO(app)
messages = [] # List to store chat messages
user_names = {} # Dictionary to store user names and colors
def generate_color():
"""Generate a random RGB color."""
r = random.randint(200, 255)
g = random.randint(100, 255)
b = random.randint(100, 255)
return f"rgb({r},{g},{b})"
def load_user_names():
"""Load user names and colors from a JSON file."""
if os.path.exists('user_names.json'):
with open('user_names.json', 'r') as f:
return json.load(f)
return {}
def save_user_names():
"""Save user names and colors to a JSON file."""
with open('user_names.json', 'w') as f:
json.dump(user_names, f)
# Load user names and colors from file on startup
user_names = load_user_names()
# Route for the home page
@app.route('/')
def index():
"""Render the index.html template and set a device ID cookie."""
resp = make_response(render_template('index.html'))
if not request.cookies.get('device_id'):
resp.set_cookie('device_id', str(uuid4()), max_age=31536000, secure=True, httponly=True) # 1 year, secure
return resp
# SocketIO event: on connect
@socketio.on('connect')
def handle_connect():
"""Handle a client's connection."""
device_id = request.cookies.get('device_id')
if device_id in user_names:
emit('user_name', {'user_name': user_names[device_id]}) # Send existing username to client
else:
emit('request_username') # Request client to set a username
# SocketIO event: set_username
@socketio.on('set_username')
def handle_set_username(data):
"""Handle setting a username for a client."""
device_id = request.cookies.get('device_id')
name = data['name']
color = generate_color() # Generate a random color for the user
user_names[device_id] = {'name': name, 'color': color} # Store username and color in dictionary
save_user_names() # Save updated user names to file
emit('user_name', {'user_name': name, 'color': color}) # Send username and color to client
# SocketIO event: message
@socketio.on('message')
def handle_message(data):
"""Handle receiving and broadcasting chat messages."""
device_id = request.cookies.get('device_id')
user_data = user_names.get(device_id, {'name': 'Unknown', 'color': 'white'}) # Default user data if not found
message = {'user_name': user_data['name'], 'msg': data['msg'], 'color': user_data['color']}
messages.append(message) # Add message to list
emit('message', message, broadcast=True) # Broadcast message to all clients
# Route to retrieve messages as JSON
@app.route('/get_messages')
def get_messages():
"""Return all chat messages as JSON."""
return jsonify(messages)
if __name__ == '__main__':
# Run the application with SocketIO, using SSL/TLS for secure communication
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('cert.pem', 'key.pem') # Load SSL certificate and private key
socketio.run(app, host='0.0.0.0', port=5000, ssl_context=context, debug=False, allow_unsafe_werkzeug=True)
Deployment: The application is set up to run on a local server using Flask’s development server with SSL/TLS support. This allows users to access the chat securely over HTTPS.
Conclusion: This project showcases the integration of Flask and SocketIO to build a robust, scalable, and secure real-time chat application. It demonstrates proficiency in web development using Python and JavaScript frameworks, offering a practical solution for modern web-based communication needs.
0 Comments