install socketio flask
Install Flask-SocketIO using pip:
pip install flask-socketio
Import necessary modules in your Flask application:
python from flask import Flask, render_template from flask_socketio import SocketIO
Create a Flask application and configure it:
python app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key'
Initialize SocketIO with the Flask application:
python socketio = SocketIO(app)
Define a route to serve your HTML page with WebSocket support:
python @app.route('/') def index(): return render_template('index.html')
Implement WebSocket events for handling client-server communication:
python @socketio.on('message') def handle_message(msg): print('Message: ' + msg) socketio.emit('message', msg)
Run the application with SocketIO support:
python if __name__ == '__main__': socketio.run(app, debug=True)
Create an HTML template for the WebSocket-enabled page (e.g., index.html): ```html
WebSocket Example
```