Skip to main content

Command Palette

Search for a command to run...

Understanding WebSockets: A Beginner’s Guide

Updated
4 min read
Understanding WebSockets: A Beginner’s Guide

WebSockets are a modern technology that makes real-time communication over the internet fast and efficient. Let’s break it down and explore why WebSockets are essential, how they work, and how they differ from traditional protocols like HTTP.

What Are WebSockets?

WebSockets are a communication protocol that allows for full-duplex (two-way) communication between a client (like a web browser) and a server. This means both the client and the server can send and receive messages at any time without waiting for the other to finish.


Why Are WebSockets Used?

WebSockets are increasingly popular because they address the limitations of older protocols like HTTP for real-time communication. Here are the main reasons for their usage:

  • Real-Time Data Exchange: Ideal for applications requiring instant updates, such as chat apps, live sports scores, or stock market tracking.

  • Reduced Latency: Unlike HTTP, WebSockets keep the connection open, reducing the delay caused by repeatedly opening and closing connections.

  • Two-Way Communication: Enables seamless interaction, such as collaborative editing in documents or multiplayer online games.

  • Scalable Architecture: Efficient resource use makes WebSockets suitable for large-scale real-time applications.


How Do WebSockets Work?

Here’s a step-by-step explanation of how WebSockets operate:

  1. Handshake:

    • The client initiates a connection with an HTTP request with a special header (“Upgrade”).

    • The server responds with status 101, if agreeing to switch the connection from HTTP to WebSocket. It responds with some error code if server doesn’t support webSocket upgrade.

Client request header look like this:

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Version: 13

upgrade field has been set to websocket and connection field has been set to upgrade, which denotes that client is requesting a websocket connection over http. sec-websocket-key is the base64 encoded value that is generated randomly.

Server will receive the request, read the websocket-key and combine with globally unique identifier and do SHA-1 hash of concatenated string. This hash value will be part of field sec-websocket-Accept if it willing to accept the connection.

Server will send the below headers in the form of handshake to the client.

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
  1. Connection Established:

    • Once the handshake is complete, the connection stays open.
  2. Real-Time Communication:

    • Both the client and server can send messages to each other anytime.

    • Messages are exchanged using lightweight frames, ensuring efficiency.

  3. Connection Closure:

    • Either the client or the server can close the connection when the communication is complete.

WebSocket has a default URI format

ws-URI =  "ws:" "//" host [ ":" port ] path [ "?" query ]
wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]

wss denotes a secure web-socket connection with TLS handshake. Separate port will be used on the client and the server side, decided by client and server.


How WebSocket different from HTTP

WebSockets and HTTP may seem similar since they both run over TCP, but their behavior is fundamentally different.

FeatureWebSocketsHTTP
ConnectionPersistent (open for long-term)Stateless (one request-response cycle)
CommunicationFull-duplex (two-way)Half-duplex (client initiates)
OverheadMinimal (after handshake)High (headers for every request)
Real-Time SuitabilityExcellentRequires polling/long-polling

The web-socket protocol is an TCP based protocol. It’s only relationship to HTTP is that its handshake is interpreted by HTTP servers as an upgrade request.


When Is HTTP Preferred Over WebSockets?

While WebSockets excel in real-time communication scenarios, HTTP is still preferred in many situations due to its simplicity and widespread use. Here are some cases where HTTP is a better choice:

  • Static Content Delivery:

    • For serving static assets like HTML, CSS, JavaScript, or images, HTTP is more straightforward and efficient.
  • Simple Request-Response:

    • For operations like form submissions, API calls, or fetching data where one request yields one response, HTTP is sufficient.
  • Short-Lived Connections:

    • For actions that do not require a persistent connection, such as loading a webpage or making occasional API requests.
  • Browser and Server Compatibility:

    • HTTP is universally supported and works seamlessly with all browsers, servers, and proxies.
  • Security and Caching:

    • HTTP benefits from established security protocols and caching mechanisms, making it ideal for delivering resources efficiently.
  • Lower Complexity:

    • HTTP does not require the additional implementation effort needed for managing WebSocket connections and messages.

Conclusion

WebSockets are a game-changer for applications that demand real-time communication. By enabling persistent and efficient two-way communication, WebSockets reduce latency and overhead, making them a go-to choice for modern web and mobile applications. While they might not replace HTTP entirely, they complement it by addressing specific use cases like live updates and interactivity. As real-time applications grow, understanding and leveraging WebSockets can be a significant advantage for developers.

More from this blog

Anish Ratnawat's Tech Blog

21 posts