WebSocket is a powerful technology for establishing bidirectional real-time communication channels between servers and clients. Below is a guide on how to integrate WebSocket into two popular frameworks, Flask and FastAPI.
Integrating WebSocket into Flask
Step 1: Install Libraries
Firstly, you need to install the flask
and flask-socketio
libraries using the following command:
pip install Flask flask-socketio
Step 2: Set Up the Application
Here's an example of how to integrate WebSocket into a Flask application:
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(message):
emit('response', {'data': message})
if __name__ == '__main__':
socketio.run(app)
In the code snippet above, we use the flask-socketio
library to create a WebSocket server. The handle_message
function is called when a client sends a message, and the server responds by emitting a response
event.
Integrating WebSocket into FastAPI
Step 1: Install Libraries
Install the fastapi
and uvicorn
libraries using the following command:
pip install fastapi uvicorn
Step 2: Set Up the Application
Here's an example of how to integrate WebSocket into a FastAPI application:
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get('/')
def get():
return HTMLResponse(content=open("index.html").read())
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Server received: {data}")
In the code snippet above, we use FastAPI to create a WebSocket server. The websocket_endpoint
function accepts WebSocket connections, listens for data sent by clients, and responds by sending data back to the client.
Conclusion
Integrating WebSocket into popular frameworks like Flask and FastAPI opens up possibilities for creating real-time applications and bidirectional communication between servers and clients.