Introduction to Web Sockets

Introduction to Web Sockets

A tiny introduction to web sockets.


When thinking about building a real-time chat feature like the one on Twitch, it's crucial that it works fast and efficiently.

The old way of checking the server every second with HTTP requests to get new messages isn't very efficient. This is mainly because HTTP uses TCP, which needs a three-step process to start a connection before any data can be sent.

This approach is too slow for apps that need instant communication and uses too many resources.

Web Sockets

Web Sockets offers a solution by creating a two-way communication channel through one persistent connection between the client and server.

Unlike HTTP requests that open and close repeatedly, WebSockets begin with an initial HTTP request from the client to the server. This request is then upgraded, indicated by the 101 Switching Protocols response status code, changing the connection from HTTP to WebSockets.

This upgrade starts a persistent connection, allowing for immediate data exchange. Messages can be sent back and forth without having to set up new connections each time, making WebSockets perfect for real-time applications like chat systems, live sports updates, or financial trading platforms.

Key Advantages of Web Sockets

  • Reduced LAtency: Messages are sent instantly without having to reconnect every time.

  • Saves Resources: Uses just one ongoing connection, cutting down on server stress and network traffic.

  • Two-way Communication: Both the client and server can start sending messages, making interactions better.