What WebSocket is

HTTP is a request-response model: the server cannot send data to the browser on its own. For live data people used polling (asking every second), which loads the server and adds latency. A WebSocket is a two-way connection that is established once and stays open: either side can send a message at any time.

The address schemes are ws:// and wss:// (with TLS). The connection starts as a regular HTTP request (Upgrade: websocket), the server answers 101 Switching Protocols and frames begin to flow over the same TCP connection.

WebSocket handshake and messages
WebSocket handshake and messages

💡 If data flows only from the server to the browser, Server-Sent Events (EventSource) are simpler. Choose WebSocket when you need two-way exchange.


Connection, events and state

A connection is created with new WebSocket(url) and driven by four events. In the example the server is an echo server (a placeholder address, use your own server).

javascript
const ws = new WebSocket('wss://echo.example.test/chat');

ws.addEventListener('open', () => {
  console.log('open');
  ws.send('hello');
});

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

ws.addEventListener('close', (event) => {
  console.log('close:', event.code);
});

The connection state lives in ws.readyState:

ValueConstantMeaning
0WebSocket.CONNECTINGHandshake in progress
1WebSocket.OPENReady, you may send
2WebSocket.CLOSINGclose() was called
3WebSocket.CLOSEDClosed or the connection failed

The error event gives no details (for security reasons) and is always followed by close; event.code shows the reason.