Introduction
WebSockets enable real-time bidirectional communication between client and server.
Python WebSocket Server
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(f"Echo: {message}")
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, "localhost", 8765)
)
asyncio.get_event_loop().run_forever()
Client Connection
// JavaScript client
const ws = new WebSocket("ws://localhost:8765");
ws.onopen = () => {
ws.send("Hello!");
};
ws.onmessage = (event) => {
console.log("Received:", event.data);
};
ws.close();
FastAPI WebSocket
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
Practice Problems
- Create WebSocket server
- Implement chat functionality
- Handle multiple connections
- Add authentication
- Broadcast to all clients