A WebSocket connection is established using the WebSocket constructor and an automatic protocol upgrade from HTTP to WebSocket (WS). The process involves: 1) Client initiates connection with 'ws://' or 'wss://' URL, 2) An HTTP handshake occurs with an 'Upgrade' header, 3) Server accepts the upgrade, 4) Connection is upgraded to WebSocket protocol. The code shows proper event handling for connection establishment, errors, and closure.