- Python installed on your machine
- Basic understanding of Python and JavaScript
- Flask and Flask-SocketIO libraries
Step 1: Set Up the Environment
- Install Flask and Flask-SocketIO:Open your terminal and run:
pip install Flask Flask-SocketIO
- Create a Project Directory:bashCopy code
mkdir chat_app cd chat_app
- 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
- Create a
templates
folder in your project directory.
mkdir templates
- Create an
index.html
file inside thetemplates
folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat Application</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.min.js"></script>
<style>
body { font-family: Arial, sans-serif; }
#messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; margin-bottom: 10px; }
#message-input { width: 80%; }
</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 += '<div>' + msg + '</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.
Leave a Reply