Welcome to our guide on using WebSockets in Python! WebSockets provide a full-duplex communication channel over a single TCP connection, enabling real-time data transfer between a client and a server. This makes WebSockets ideal for applications such as chat apps, online gaming, or any service requiring real-time updates. In this post, we’ll cover the basics of WebSockets, how to implement them using popular Python frameworks like Flask and FastAPI.
1. What are WebSockets?
WebSockets enable interactive communication sessions between the client and server. Unlike traditional HTTP requests, where the client sends a request and waits for a response, WebSockets allow data to flow both ways without the overhead of repeated connection setups.
2. Setting Up Your Environment
To work with WebSockets in Python, you can choose to use libraries such as Flask-SocketIO
for Flask or FastAPI
with the WebSocket
class. Start by installing the necessary packages:
pip install flask flask-socketio fastapi uvicorn
3. Implementing WebSockets with Flask-SocketIO
Let’s start by creating a simple WebSocket server using Flask:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(msg):
print('Received message:', msg)
emit('response', {'data': 'Message received!'})
if __name__ == '__main__':
socketio.run(app)
This code sets up a Flask application with SocketIO, where a message sent by a client is received and a response is sent back.
3.1 Creating an HTML Client
Next, create a simple HTML client that connects to your Flask WebSocket server. Save the following code as templates/index.html
:
WebSocket Chat
WebSocket Chat
4. Implementing WebSockets with FastAPI
FastAPI provides built-in support for WebSockets. Here’s how to create a simple WebSocket server:
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/")
async def get():
return HTMLResponse('''
WebSocket Chat
WebSocket Chat