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>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat App</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<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%; }
</style>
</head>
<body>
<h1>Chat Room</h1>
<ul id="messages"></ul>
<input id="message-input" autocomplete="off" placeholder="Type a message..." />
<button id="send-button">Send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
<script src="static/script.js"></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.
Leave a Reply