To enable WebSockets, install Flask-SocketIO:
pip install flask flask-socketio
app.py
from flask import Flask, render_template
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret!"
socketio = SocketIO(app)
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("message")
def handle_message(msg):
print(f"Message received: {msg}")
send(msg, broadcast=True) # Sends message to all clients
if __name__ == "__main__":
socketio.run(app, debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask WebSocket Chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
<h2>Real-Time Chat</h2>
<input id="message" type="text" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
var socket = io.connect("http://" + document.domain + ":" + location.port);
socket.on("message", function(msg) {
let li = document.createElement("li");
li.innerText = msg;
document.getElementById("messages").appendChild(li);
});
function sendMessage() {
let msg = document.getElementById("message").value;
socket.send(msg);
document.getElementById("message").value = "";
}
</script>
</body>
</html>
python app.py
For deployment, use eventlet or gevent:
pip install eventlet
Modify app.py
:
socketio.run(app, host="0.0.0.0", port=5000, debug=True)
In this guide, we learned how to:
✅ Set up Flask-SocketIO for WebSockets.
✅ Create a real-time chat app with Flask and JavaScript.
✅ Use SocketIO for instant message broadcasting.
✅ Deploy the WebSocket app using eventlet for scalability.
This setup is perfect for real-time dashboards, notifications, and live updates! 🚀