Understanding WebSockets: A Beginner’s Guide to Real-Time Web Communication day 38 of system design basics
Vincent Tommi

Vincent Tommi @vincenttommi

About: Backend-Developer

Location:
Nairobi-Kenya
Joined:
Apr 2, 2023

Understanding WebSockets: A Beginner’s Guide to Real-Time Web Communication day 38 of system design basics

Publish Date: Aug 27
5 0

Imagine playing an online game where the leaderboard updates instantly as players score points, or chatting with friends on a messaging app where messages pop up without refreshing the page. These seamless, real-time experiences feel almost magical—but how do they work? The answer is often WebSockets, a powerful technology that enables instant, two-way communication between a web browser and a server.

In this beginner-friendly guide, we’ll explore what WebSockets are, how they work, why they’re used, how they compare to other methods, their challenges, and how to implement them with Django and JavaScript. Let’s dive in!

What Are WebSockets?

WebSockets are a communication protocol that creates a persistent, two-way connection between a client (like your web browser) and a server. Unlike traditional HTTP, where the client sends a request and waits for a response, WebSockets allow both sides to send messages anytime, making real-time features possible.

Think of WebSockets like a phone call: once the call is connected, both people can talk and listen whenever they want, without hanging up and redialing. This makes WebSockets perfect for apps like live chat, online games, or stock market tickers.

How Do WebSockets Work?
Let’s break down the WebSocket process step-by-step in a way that’s easy to understand.

*Step-by-Step Process
*

  • Handshake: The client (your browser) sends a special HTTP request to the server, asking to switch to the WebSocket protocol. This request includes an "Upgrade" header that says, “Hey, let’s use WebSockets!”

If the server supports WebSockets, it responds with an HTTP 101 status code, agreeing to switch protocols. This is called the handshake.

  • Connection: After the handshake, a WebSocket connection is created. This connection stays open, allowing both the client and server to send messages whenever they want.

  • Data Transfer: Messages are sent in small packets called frames, which are lightweight compared to HTTP requests. This means less data is sent, making communication fast and efficient.

  • Closure: Either the client or server can close the connection when it’s no longer needed, using a special “close” message.

Why Use WebSockets?
WebSockets shine in situations where speed and real-time updates matter. Here’s why developers love them:

  • Real-Time Updates: Perfect for apps like chat, gaming, or live notifications where updates need to happen instantly.

  • Low Latency: Since the connection stays open, there’s no delay from setting up new connections for each message.

  • Efficient: WebSockets use less data than repeatedly asking the server for updates (unlike older methods).

  • Two-Way Communication: Both the client and server can send messages anytime, making apps more interactive.

  • Lightweight: WebSocket messages have tiny headers (as little as 2 bytes), so they don’t waste bandwidth.

WebSockets vs. Other Methods

To understand why WebSockets are special, let’s compare them to other common communication methods: HTTP, polling, and long-polling.

HTTP

  • How it works: The client sends a request, the server responds, and the connection closes. It’s like mailing a letter and waiting for a reply.

  • Downside: It’s slow for real-time apps because each update requires a new request, adding delay and overhead.

Long-Polling

  • How it works: The client sends a request, and the server holds it open until there’s new data or a timeout. Then the client sends a new request.

  • Downside: It’s better than polling but still requires new requests after each update, which adds latency and server load.

WebSockets

  • How it works: A single connection stays open, allowing instant, two-way communication.

  • Advantages: Low latency, efficient, and perfect for real-time apps.

Where Are WebSockets Used?

WebSockets power many real-time features we use daily. Here are some examples:

  • Chat Apps: Apps like Slack use WebSockets to deliver messages instantly, so you see new messages without refreshing.

  • Live Notifications: Social media platforms push notifications for likes, comments, or messages as soon as they happen.

  • Online Games: Multiplayer games use WebSockets to sync player actions in real time, ensuring everyone sees the same game state.

  • Financial Apps: Stock or crypto apps stream live market data, like price changes, using WebSockets.

  • Collaboration Tools: Tools like Google Docs use WebSockets to let multiple people edit a document at the same time.

  • IoT Devices: Smart devices (like home sensors) use WebSockets to send data to servers or receive commands instantly.

  • Live Streaming: WebSockets handle real-time chat or viewer counts during live video broadcasts.

Challenges of Using WebSockets
While WebSockets are powerful, they come with some challenges:

  • Network Issues: If the connection drops (e.g., due to a bad Wi-Fi signal), you need a plan to reconnect automatically.

  • Proxies and Firewalls: Some networks block WebSocket connections, so you might need a backup method like long-polling.

  • Scalability: Handling thousands of open connections can strain servers. Tools like load balancers can help.

  • Security: WebSockets need secure connections (using wss://) to prevent attacks like hijacking or denial-of-service.

To address these, developers often add heartbeat messages (like sending “ping” to check if the connection is alive) and secure their apps with proper authentication.

Let’s Build a Simple WebSocket App
Let’s create a simple WebSocket app using Django for the server and JavaScript for the client. The app will be a basic chat where the server sends a welcome message, and the client can send messages that the server echoes back.

Prerequisites

  • Python 3.8+ and Django installed.

  • The channels library for WebSocket support in Django.

  • A basic Django project setup.

Run these commands to set up your environment:

pip install django channels
Enter fullscreen mode Exit fullscreen mode

Server-Side (Django)
Set up Django Channels: Add channels to your Django project. Update your settings.py:

INSTALLED_APPS = [
    ...,
    'channels',
]

ASGI_APPLICATION = 'your_project_name.asgi.application'
Enter fullscreen mode Exit fullscreen mode

1 Create an asgi.py file in your project directory (e.g., your_project_name/asgi.py):

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
import your_app_name.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(
        your_app_name.routing.websocket_urlpatterns
    ),
})
Enter fullscreen mode Exit fullscreen mode

2 Create a Consumers File: Create a consumers.py file in your app directory (e.g., your_app_name/consumers.py):

from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        self.send(text_data="Welcome to the WebSocket server!")

    def disconnect(self, close_code):
        print("Client disconnected")

    def receive(self, text_data):
        print(f"Received: {text_data}")
        self.send(text_data=f"Server received: {text_data}")
Enter fullscreen mode Exit fullscreen mode

3 Define WebSocket Routing: Create a routing.py file in your app directory (e.g., your_app_name/routing.py):

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()),
]

Enter fullscreen mode Exit fullscreen mode

4 Update URLs: Ensure your project’s urls.py includes the app’s URLs, though WebSockets use ASGI routing. Run the Django server with:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Note: For production, you’ll need a channel layer (e.g., Redis) and a server like Daphne or Uvicorn. For this demo, the in-memory channel layer works fine.

Client-Side (JavaScript)

Create an HTML file (e.g., templates/chat.html) in your Django app:

<!DOCTYPE html>
<html>
<head>
  <title>WebSocket Chat</title>
</head>
<body>
  <h1>WebSocket Chat</h1>
  <input type="text" id="messageInput" placeholder="Type a message">
  <button onclick="sendMessage()">Send</button>
  <ul id="messages"></ul>

  <script>
    const ws = new WebSocket('ws://localhost:8000/ws/chat/');

    ws.onopen = () => {
      console.log('Connected to server');
    };

    ws.onmessage = (event) => {
      const message = event.data;
      const li = document.createElement('li');
      li.textContent = message;
      document.getElementById('messages').appendChild(li);
    };

    ws.onclose = () => {
      console.log('Disconnected from server');
    };

    function sendMessage() {
      const input = document.getElementById('messageInput');
      ws.send(input.value);
      input.value = '';
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Add a URL pattern in your app’s urls.py to serve this template:

from django.urls import path
from . import views

urlpatterns = [
    path('chat/', views.chat_view, name='chat'),
]
Enter fullscreen mode Exit fullscreen mode

Create a view in views.py:

from django.shortcuts import render

def chat_view(request):
    return render(request, 'chat.html')
Enter fullscreen mode Exit fullscreen mode

Try It Out

Start your Django server:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Conclusion

WebSockets are a game-changer for building real-time web apps, from chat platforms to live games. Using Django’s channels library, you can easily add WebSocket support to your Python projects. They offer low-latency, two-way communication that makes user experiences feel instant and engaging. While they come with challenges like scalability and network reliability, careful planning (like adding secure connections and reconnection strategies) can solve these issues.

Now that you’ve learned the basics and built a simple Django WebSocket app, why not try creating your own real-time project? Share your ideas or questions in the comments below, and let’s keep the conversation going on

Comments 0 total

    Add comment