WebSocket connections and lifecycle
Quick answer
WebSocket provides a persistent, two-way channel between a browser and a server. Unlike a single fetch request, either endpoint can send messages while the connection is open.
How it works
Create new WebSocket(url, [protocols]). Use wss on secure production pages; the local lab uses ws on loopback. The constructor begins connecting and returns before the handshake completes. Wait for the open event before sending. readyState distinguishes CONNECTING (0), OPEN (1), CLOSING (2), CLOSED (3). An error event is not a detailed network diagnosis; close provides code, reason and wasClean, but clean closure does not establish that the application processed every message. Close unused connections. Authentication and server-side origin validation are separate from opening the channel.
Local examples
Run in the isolated projects/realtime-lab development origin (see README). NOT RUN in local validation; expected result is instructional.
(async () => {const url=new URL("/ws",location.href);url.protocol=location.protocol==="https:"?"wss:":"ws:";const ws=new WebSocket(url);try{await new Promise((ok,no)=>{ws.onopen=ok;ws.onerror=()=>no(new Error("connection failed"));});console.log(ws.readyState===WebSocket.OPEN);}finally{ws.close();}})()Expected console output (not executed locally):
trueAfter the open event the socket is open. Requires the local echo server.
Run in a fresh browser document with local synthetic data. Actual ByteMind editor support is unverified.
(async () => {console.log([WebSocket.CONNECTING,WebSocket.OPEN,WebSocket.CLOSING,WebSocket.CLOSED].join(","));})()Expected console output:
0,1,2,3The state constants describe the lifecycle; no connection is opened.
Common mistakes
Do not send before OPEN or treat a successful handshake as authorization. Avoid unbounded reconnect loops.
Practice
Run the local lab, observe CONNECTING and OPEN, request closure and record the close code.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
WebSocket connections and lifecycle — Knowledge Check
Apply the concept and reason about local example output.
When should a browser send through a newly constructed WebSocket?
What does a successful WebSocket handshake establish?
What does wasClean on a CloseEvent establish?
What is the expected console output of WebSocket connections and lifecycle example 1?
(async () => {const url=new URL("/ws",location.href);url.protocol=location.protocol==="https:"?"wss:":"ws:";const ws=new WebSocket(url);try{await new Promise((ok,no)=>{ws.onopen=ok;ws.onerror=()=>no(new Error("connection failed"));});console.log(ws.readyState===WebSocket.OPEN);}finally{ws.close();}})()What is the expected console output of WebSocket connections and lifecycle example 2?
(async () => {console.log([WebSocket.CONNECTING,WebSocket.OPEN,WebSocket.CLOSING,WebSocket.CLOSED].join(","));})()