Software-Engineering

WebSockets

What are WebSockets?

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011.

Unlike HTTP, which is request-response (client asks, server answers), WebSockets allow for persistent, bi-directional communication. The server can send data to the client without the client requesting it first.

How it Works

  1. Handshake: The connection starts as a standard HTTP request. The client sends a request with an Upgrade: websocket header.
  2. Upgrade: If the server supports it, it responds with 101 Switching Protocols, and the connection is upgraded from HTTP to the WebSocket protocol.
  3. Persistent Connection: The TCP connection remains open.
  4. Frames: Data is exchanged in “frames”. Both client and server can send frames at any time.
  5. Close: Either side can send a close frame to terminate the connection.

Why We Need It & When to Use

HTTP is inefficient for real-time applications because of the overhead of opening a new connection for every request and the inability of the server to push data.

Use WebSockets when:

Other Options

Pros and Cons

Pros

Cons