WebSockets

Web DevelopmentReal-timeFree Lesson

Advertisement

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

  1. Create WebSocket server
  2. Implement chat functionality
  3. Handle multiple connections
  4. Add authentication
  5. Broadcast to all clients

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement