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.
💡 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).
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:
| Value | Constant | Meaning |
|---|---|---|
| 0 | WebSocket.CONNECTING | Handshake in progress |
| 1 | WebSocket.OPEN | Ready, you may send |
| 2 | WebSocket.CLOSING | close() was called |
| 3 | WebSocket.CLOSED | Closed or the connection failed |
The error event gives no details (for security reasons) and is always followed by close; event.code shows the reason.