Video in progress

How is a WebSocket connection opened between a browser and a server?

The client sends a normal HTTP GET with the Upgrade: websocket and Connection: Upgrade headers. If the server agrees, it returns 101 Switching Protocols and that same TCP connection switches to the WebSocket protocol.

📖 Answer

The first request you see in the browser devtools looks roughly like this:

GET /ws/chat HTTP/1.1
Host: api.javaintervyu.uz
Origin: https://javaintervyu.uz
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: q4xkcO32u266gldTuKaSOw==

If the server agrees, the response comes back with no body:

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: fA9dggdnMPU79lJgAE3W4TRnyDM=

After that 101 line the HTTP conversation is over. Frames now travel over the very same TCP socket. No new port is opened, so the traffic passes through 80/443 without trouble.

If the server returns some other status (say 403 because the token is missing), the browser calls onerror first and then onclose. To see what happened, turn on the "WS" filter in the Network tab and look at the status code of that request.