Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 122 Β· Web APIs

WebSockets

Learn the WebSocket API for two-way, real-time messaging. Open a connection, send and receive data, handle close codes, and choose between WebSockets, SSE and fetch.

A chat app, a multiplayer game or a shared whiteboard has one thing in common: both sides talk all the time. The browser sends a move or a message, and the server sends everyone else's moves back, many times per second. Ordinary HTTP requests are too slow and heavy for this, and Server-Sent Events only carry data from the server to the browser.

WebSockets give you a permanent, two-way connection. After a quick handshake, the browser and the server can each send a message at any moment, with very little overhead per message. In this lesson you will learn the WebSocket object, its four events, how to send text and binary data, what the close codes mean, and how to choose between WebSockets, SSE and plain fetch().

The editors on this page have no WebSocket server to talk to. The first live example shows exactly what happens when a connection fails. The second uses a stand-in "echo server" with the same API as a real WebSocket. The read-only snippets work unchanged against a real server.

How a WebSocket connection starts

A WebSocket begins life as an ordinary HTTP request with a special header asking the server to upgrade the connection:

TEXT
GET /chat HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: (random value chosen by the browser)
Sec-WebSocket-Version: 13

If the server agrees, it answers with status 101 Switching Protocols. From then on, the same connection stops speaking HTTP and carries small WebSocket frames in both directions until one side closes it. The browser handles all of this; you never write these headers yourself.

WebSocket URLs use their own schemes:

  • wss:// is encrypted, like https://. Use it for every real site.
  • ws:// is unencrypted, like http://. Pages served over HTTPS are not allowed to open ws:// connections, so it is only useful for local testing.

Opening a connection

Create a WebSocket with the server's URL. The connection opens in the background, and the object fires events as things happen:

JavaScript
const socket = new WebSocket('wss://chat.example.com/room/42');

socket.addEventListener('open', () => {
  socket.send('Hello, everyone!');
});

socket.addEventListener('message', (event) => {
  console.log('Received:', event.data);
});

socket.addEventListener('close', (event) => {
  console.log('Closed with code', event.code, 'reason:', event.reason);
});

socket.addEventListener('error', () => {
  console.log('Something went wrong.');
});

The four events are:

Event When it fires Useful properties
open The handshake succeeded; you can send now (none)
message A message arrived from the server data
error Something failed; a close event always follows (none, on purpose)
close The connection is closed code, reason, wasClean

The error event deliberately contains no details, so a malicious page can't use WebSockets to probe the network. Look at the close event that follows it to learn more.

You can pass a second argument with one or more subprotocols, names that your client and server agree on, such as new WebSocket(url, ['chat-v2']). After opening, socket.protocol tells you which one the server picked.

Connection states

socket.readyState tells you where the connection is:

Value Constant Meaning
0 WebSocket.CONNECTING The handshake is in progress
1 WebSocket.OPEN Ready to send and receive
2 WebSocket.CLOSING The closing handshake is in progress
3 WebSocket.CLOSED Closed, or never opened

Calling send() while the state is still CONNECTING throws an InvalidStateError. That is why the snippet above sends its first message inside the open handler.

Run the next example to watch a connection fail. It tries a host on the .invalid domain, which is reserved and can never exist, so the connection is guaranteed to fail.

Watching a connection fail

The close event arrives with code 1006. That code never travels over the network; the browser uses it to say "the connection ended abnormally, without a proper closing handshake". It is what you will see when a server is unreachable, crashes or the network drops.

Sending and receiving data

send() accepts text or binary data:

JavaScript
socket.send('plain text');
socket.send(JSON.stringify({ type: 'move', x: 3, y: 7 }));   // structured data as JSON
socket.send(new Uint8Array([1, 2, 3]));                      // binary (typed array)
socket.send(fileInput.files[0]);                             // a Blob or File

Incoming text arrives as a string in event.data. Incoming binary data arrives as a Blob by default; set socket.binaryType = 'arraybuffer' if you prefer an ArrayBuffer.

WebSockets carry raw messages and nothing more. There are no URLs, methods or status codes inside the connection, so most apps invent a tiny protocol: every message is a JSON object with a type field that says what it is.

JavaScript
socket.addEventListener('message', (event) => {
  const message = JSON.parse(event.data);

  switch (message.type) {
    case 'chat':   addChatLine(message.user, message.text); break;
    case 'joined': showNotice(`${message.user} joined`); break;
    case 'typing': showTypingIndicator(message.user); break;
  }
});

send() doesn't wait for the data to leave. It adds the message to a queue and returns at once. socket.bufferedAmount tells you how many bytes are still waiting, which is useful if you stream lots of data and want to slow down when the network can't keep up.

The example below builds a small chat window around a FakeWebSocket class: an "echo server" that behaves like a real socket (same constructor, readyState, send(), close() and the four events) and answers each message after a short delay. Change the first line of the script to new WebSocket('wss://your-server.example/chat') and the rest of the code works with a real server.

A chat window (simulated server)

Closing a connection

Either side can close the connection. In the browser, call close() with an optional code and reason:

JavaScript
socket.close(1000, 'User logged out');

From the page, you may only use code 1000 or a code from 3000 to 4999 (the range for libraries and your own apps). The reason must be short: at most 123 bytes of UTF-8 text. These are the codes you will meet most often in close events:

Code Meaning
1000 Normal closure; the job is done
1001 Going away (the server is shutting down, or the user left the page)
1006 Closed abnormally, with no closing handshake (set by the browser, never sent)
1008 Policy violation (for example, not authorized)
1011 The server hit an unexpected error
4000–4999 Defined by your own application

event.wasClean is true when both sides completed the closing handshake properly.

Reconnecting

Unlike EventSource, a WebSocket never reconnects by itself. When the connection closes unexpectedly, you have to open a new one. Wait a little longer after each failure (a pattern called exponential backoff) so that a crowd of clients doesn't overwhelm a server that is just restarting:

JavaScript
let attempts = 0;

function connect() {
  const socket = new WebSocket('wss://chat.example.com/room/42');

  socket.addEventListener('open', () => { attempts = 0; });

  socket.addEventListener('close', (event) => {
    if (event.code === 1000) return;                  // closed on purpose: stay closed
    const delay = Math.min(30000, 1000 * 2 ** attempts) + Math.random() * 1000;
    attempts++;
    setTimeout(connect, delay);                       // 1 s, 2 s, 4 s ... up to 30 s
  });

  return socket;
}

connect();

The small random extra delay spreads clients out so they don't all reconnect in the same instant. After reconnecting, the app usually has to catch up on anything it missed, for example by fetching the latest chat messages.

WebSockets, SSE or fetch?

All three move data between a browser and a server. Pick the simplest one that does the job:

fetch() Server-Sent Events WebSockets
Direction Browser asks, server answers Server to browser Both ways, at any time
Connection One request per exchange One long-lived HTTP response One long-lived upgraded connection
Data Anything Text Text and binary
Reconnects automatically Not applicable Yes, with Last-Event-ID No, you write it
Works with normal HTTP servers, caches and proxies Yes Yes Needs a WebSocket-aware server
Good for Loading data, submitting forms, most APIs Notifications, feeds, live dashboards, streamed text Chat, games, collaborative editing, live cursors

A useful rule of thumb: if the browser only occasionally sends something, fetch() for sending plus SSE for receiving is often simpler than WebSockets. Reach for WebSockets when the browser sends frequently, or when you need low-latency two-way traffic.

Treat every incoming message as untrusted. Parse JSON inside try...catch, check the fields you expect, and insert text with textContent, never innerHTML. On the server, check the user's identity when the connection opens: the WebSocket handshake doesn't follow CORS rules, so servers must verify the Origin header themselves.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does a WebSocket give you that Server-Sent Events do not?

    WebSockets are two-way. SSE is one-way (server to browser), but it does reconnect automatically and uses plain HTTP.
  2. 2. You call socket.send() immediately after new WebSocket(url). What happens?

    While readyState is CONNECTING, send() throws. Send your first message inside the open event handler.
  3. 3. A close event reports code 1006. What does it mean?

    1006 is set by the browser when the connection drops or never opened properly. It is never sent by a server.
  4. 4. Which URL should a page on an HTTPS site use for its WebSocket?

    wss:// is the encrypted WebSocket scheme. HTTPS pages can't open unencrypted ws:// connections.
  5. 5. A news site only needs to push breaking-news alerts to readers. What is the simplest good choice?

    The data flows one way, from server to browser, which is exactly what SSE is designed for, with reconnection built in.

Summary

  • A WebSocket starts as an HTTP request that is upgraded (status 101) into a permanent, two-way connection. Use wss:// on real sites.
  • new WebSocket(url) fires open, message, error and close; check readyState before sending.
  • send() takes strings, typed arrays, ArrayBuffers and Blobs; a JSON message with a type field is the usual protocol.
  • Close with close(code, reason); the close event reports code, reason and wasClean. Code 1006 means an abnormal drop.
  • WebSockets don't reconnect on their own: use exponential backoff.
  • Use fetch() for request/response, SSE for server pushes, and WebSockets for constant two-way traffic.

Next lesson: IndexedDB, the browser's built-in database for storing large amounts of structured data.