DEV Community

Nilotpal Baishya
Nilotpal Baishya

Posted on

I Finally Understood How WebSockets Actually Work

I've heard about WebSockets many times. They're used in chat applications, live notifications, multiplayer games, and pretty much anything that needs real-time communication.

But whenever I searched for an explanation, I kept seeing the same definition:

"WebSockets provide full-duplex communication over a single, persistent connection."

Okay, but what does that actually mean?

I wanted to understand what happens behind the scenes, so I decided to build a small real-time chat application using FastAPI.

Here's what I learned.

The problem with traditional HTTP

With normal HTTP, the client sends a request, the server processes it, and then sends back a response.

But imagine building a chat application with this approach.

How would the client know when someone sends a new message?

One solution is polling. The client keeps sending requests to the server asking if there's anything new.

But that means making repeated requests, even when nothing has changed.

WebSockets solve this differently.

Instead of repeatedly asking the server for updates, the client establishes a persistent connection that stays open. Both the client and server can send messages whenever they need to.

How does a WebSocket connection start?

Interestingly, WebSockets begin with an HTTP handshake.

The client sends a request asking the server to upgrade the connection to the WebSocket protocol.

If the server accepts, it responds with:

HTTP/1.1 101 Switching Protocols
Enter fullscreen mode Exit fullscreen mode

This means the protocol has been upgraded.

After that, the client and server can communicate through the same connection without creating a new HTTP request for every message.

In JavaScript, establishing a connection is surprisingly simple:

const socket = new WebSocket("ws://localhost:8000/ws");
Enter fullscreen mode Exit fullscreen mode

And that's where the interesting part begins.

Understanding the Connection Manager

When I started experimenting with WebSockets, I wanted to make two browser tabs communicate with each other.

Initially, I wondered how the server would know which clients were connected.

That's when I came across the idea of a Connection Manager.

A Connection Manager keeps track of active WebSocket connections.

Here's a simplified implementation using FastAPI:

from fastapi import WebSocket

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

    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)
Enter fullscreen mode Exit fullscreen mode

Nothing too complicated.

When a client connects, we accept the connection and store it.

When we broadcast a message, we iterate through the active connections and send the message to each client.

That's when something finally clicked for me.

The server maintains separate connections for each client. It doesn't need to establish a new connection every time someone sends a message.

What about multiple chatrooms?

After getting the basic implementation working, I wanted to take it a step further.

What if users could join different chatrooms?

For example, users A and B join room ABC123, while user C joins room XYZ789.

A message from user A shouldn't reach user C.

To achieve this, we can maintain a dictionary of rooms:

rooms = {
    "ABC123": [websocket_1, websocket_2],
    "XYZ789": [websocket_3]
}
Enter fullscreen mode Exit fullscreen mode

Now the server can broadcast messages only to the connections belonging to a particular room.

The interesting thing is that WebSockets themselves don't understand chatrooms.

A WebSocket is simply a communication channel. Room management and message routing are application-level logic that we build on top of it.

A few things I learned

After experimenting with multiple clients and chatrooms, these things became much clearer:

  • Every connected client has its own WebSocket connection.
  • A connection can carry multiple messages throughout its lifetime.
  • Broadcasting and sending a private message are different operations.
  • Disconnected clients need to be removed from the connection manager.
  • In-memory connection management has limitations when an application runs across multiple server instances. That's where tools like Redis can become useful.

Final thoughts

I initially thought WebSockets were just a way to send messages instantly.

But building something myself helped me understand that there's more to real-time communication than the protocol itself.

You also need to think about connection management, message routing, disconnections, rooms, and eventually distributed communication.

I'm still learning, but I now have a much better understanding of what's happening behind the scenes.

And honestly, that's what I enjoy most about building things: concepts that once seemed confusing start making sense when you actually implement them.

Top comments (0)