Understanding WebSockets using Python

keshavadk

keshavadk

Posted on September 8, 2024

Understanding WebSockets using Python

Introduction

In today’s digital landscape, where real-time communication is important. traditional HTTP falls short due to its request-response model and inherent latency. As businesses and applications increasingly demand instantaneous data transfer — whether it’s live stock updates, multiplayer gaming, or collaborative tools — WebSockets have emerged as a game-changing technology. Unlike HTTP, WebSockets enable full-duplex, bi-directional communication, allowing both the server and client to send and receive messages in real-time over a single, persistent connection. This not only reduces overhead but also significantly improves the performance and responsiveness of web applications.

What is WebSocket

WebSocket is a communication protocol that provides full-duplex communication channels over a single, long-lived TCP connection. This means that once a WebSocket connection is established between a client and a server, both parties can send and receive data simultaneously and continuously without the need to reopen a connection. WebSocket was designed to be efficient and low-latency, making it ideal for real-time applications.

Why WebSocket ?

WebSockets are used in scenarios where real-time communication between a client and a server is needed. Unlike traditional HTTP, which follows a request-response model where the client must initiate every request, WebSockets allow for bi-directional communication. This makes WebSockets particularly useful in applications where data needs to be pushed from the server to the client in real time without the client having to request it.

Real world Use Cases

  • Chat Applications: WebSockets are commonly used in chat applications where messages need to be sent and received in real time without delay.
  • Live Streaming: WebSockets can be used to stream live video or audio, allowing the server to push new content to the client as it becomes available.
  • Collaborative Platforms: In collaborative tools like Google Docs, WebSockets allow multiple users to see real-time changes made by others without needing to refresh the page.

WebSockets vs HTTP

Communication Model

  • HTTP: Follows a request-response model where the client initiates a request, and the server responds. After the response, the connection is closed.
  • WebSockets: WebSockets provide a full-duplex, long-lived connection where both the client and server can send and receive data continuously without reopening the connection each time.

Connection Handling

  • HTTP: Each request opens a new connection, and the connection is closed after the response.
  • WebSockets: After the initial handshake (using HTTP), the connection is kept open, allowing real-time communication without the need for re-establishing connections.

Efficiency

  • HTTP: Suitable for one-time communication or transactions where requests are infrequent. It is stateless, so for continuous communication, techniques like long-polling are used, which can be resource-intensive.
  • WebSockets: WebSockets are efficient for real-time and bi-directional communication since the connection is kept open. They use fewer resources compared to techniques like long-polling.

Latency

  • HTTP: There is always a delay (latency) as the client must request, and the server must respond. This is inefficient for real-time use cases.
  • WebSockets: After the connection is established, data can flow almost instantly between client and server, reducing latency and making it ideal for real-time applications.

Use Case

  • HTTP: Best suited for traditional web applications where requests are initiated by the client (e.g., REST APIs).
  • WebSockets: Ideal for real-time applications like chat apps, stock trading platforms, live dashboards, and online gaming.

Advantages of WebSockets

  1. Real-Time Communication: WebSockets allow for real-time, low-latency communication, making them ideal for applications that need instant updates.
  2. Bi-Directional Data Flow: Both client and server can send and receive data at any time, unlike HTTP where the server can only respond to client-initiated requests.
  3. Reduced Overhead: By keeping the connection open, WebSockets reduce the need to repeatedly establish new HTTP connections, saving bandwidth and reducing latency.
  4. Efficiency: WebSockets use fewer resources compared to long-polling or HTTP requests for continuous data transfer.
  5. Scalability: WebSockets can handle many concurrent connections efficiently, making them suitable for scalable real-time applications.

How WebSockets Work

  1. Handshake: A WebSocket connection starts with an HTTP handshake. The client sends a request to the server with an Upgrade header to switch the connection protocol from HTTP to WebSocket.
  2. Connection Established: After the handshake, the connection is established. The server and client maintain a persistent, open TCP connection.
  3. Full-Duplex Communication: Once the WebSocket connection is open, data can be sent back and forth simultaneously. Both the server and the client can initiate communication at any time.
  4. Close Connection: Either the server or the client can close the connection when it’s no longer needed. This terminates the session and releases the resources.

Use Cases for WebSockets

  1. Chat Applications: Instant messaging services like WhatsApp and Slack use WebSockets for real-time messaging between users.
  2. Live Updates: WebSockets power real-time data updates in applications such as financial trading platforms (stock prices), sports scores, or live news feeds.
  3. Collaborative Tools: WebSockets enable real-time updates in collaborative tools like Google Docs or Figma, where multiple users can edit a document simultaneously.
  4. Online Gaming: Multiplayer games rely on WebSockets for real-time player actions and interactions.
  5. IoT and Sensor Data: Devices with real-time data streaming (e.g., IoT devices, weather sensors) use WebSockets to send continuous updates.

Building Real-Time Applications with Python and WebSockets

Let’s build a real-time application using WebSockets with Python (using FastAPI) and Streamlit.

1. Set Up FastAPI WebSocket Server

This code sets up a WebSocket server using FastAPI.

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.broadcast(f"Message: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
Enter fullscreen mode Exit fullscreen mode

This WebSocket server can handle multiple connections and broadcast messages to all connected clients.

2. Streamlit Frontend

Now, let’s build a real-time application using Streamlit that connects to the WebSocket server and receives live updates.

import streamlit as st
import asyncio
import websockets

async def websocket_receive():
    uri = "ws://localhost:8000/ws"
    async with websockets.connect(uri) as websocket:
        while True:
            message = await websocket.recv()
            st.write(f"Received: {message}")

st.title("Real-Time WebSocket Client")

if st.button("Connect to WebSocket"):
    st.write("Connected!")
    asyncio.run(websocket_receive())
Enter fullscreen mode Exit fullscreen mode

Explanation: When the user clicks the “Connect to WebSocket” button, the Streamlit frontend establishes a connection with the WebSocket server and listens for messages.

3. Running the Application

Run the FastAPI server:

uvicorn server:app --reload
Enter fullscreen mode Exit fullscreen mode

Run the Streamlit app:

streamlit run your_script.py
Enter fullscreen mode Exit fullscreen mode

Key Steps in Real-Time Communication:

  • WebSocket Setup: The WebSocket server runs and accepts connections.
  • Streamlit Connection: Streamlit frontend initiates a connection to the WebSocket server.
  • Full-Duplex Communication: Both client (Streamlit) and server (FastAPI) can send/receive messages in real-time.
💖 💪 🙅 🚩
keshavadk
keshavadk

Posted on September 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Understanding WebSockets using Python
python Understanding WebSockets using Python

September 8, 2024