← Lessons

quiz vs the machine

Gold1450

Frontend

The Web Sockets API

Open a persistent two way channel for real time messaging.

5 min read · core · beat Gold to climb

Full duplex communication

The WebSocket API opens a persistent, bidirectional connection between browser and server over a single TCP connection. Unlike polling, both sides can send messages at any time.

  • The connection begins as an HTTP upgrade handshake
  • Use the ws or secure wss scheme
  • Messages flow as text or binary frames
  • The connection stays open until either side closes it

The event model

A WebSocket emits four key events.

  • open: the connection is established and ready
  • message: data arrived from the server
  • error: a problem occurred
  • close: the connection ended, with a code and reason

When to choose it

WebSockets shine for chat, live dashboards, multiplayer games, and collaborative editing, anywhere low latency two way updates matter. For one directional server pushes only, Server Sent Events can be simpler.

Key idea

A WebSocket upgrades from HTTP to a persistent full duplex channel using open, message, error, and close events, ideal for low latency real time apps.

Check yourself

Answer to earn rating on the learn ladder.

1. How does a WebSocket connection begin?

2. What advantage do WebSockets have over repeated polling?

3. Which event signals that a WebSocket is ready to send data?