Explicando o handshake do WebSocket
Analise o processo de handshake baseado em HTTP que atualiza uma conexão HTTP padrão para uma conexão WebSocket.
Explicando o handshake do WebSocket é uma aula grátis de WebSockets & Realtime Systems Programming no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de WebSockets & Realtime Systems Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de WebSockets & Realtime Systems Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Handshake: The Connection Upgrade
Imagine you're calling a friend, but instead of just talking, you first agree on a secret language. The WebSocket handshake is similar!
It's the crucial initial step where your browser (client) and a server agree to switch from a standard HTTP connection to a WebSocket connection.
Beyond HTTP's Limitations
Traditional HTTP is designed for short, one-off requests and responses. Think of loading a webpage – you ask, the server sends, and the connection closes.
- One-way: Client requests, server responds.
- Short-lived: Connection closes after each interaction.
- Overhead: Each new request needs to set up a new connection.
WebSockets need a persistent, two-way street for real-time data.
Client Initiates the Upgrade
The handshake begins with the client (your browser) sending a regular HTTP GET request to the server. But it's not truly "regular"!
This request includes special HTTP headers that signal the client's intention to "upgrade" to the WebSocket protocol. It's like adding a special note to your call asking to switch to the secret language.
Signaling the Intent to Switch
Two key headers clearly tell the server the client wants a WebSocket connection:
Upgrade: websocket: This header specifies the protocol the client wants to switch to.Connection: Upgrade: This header is a general HTTP header that indicates the client wishes to upgrade or switch protocols.
Together, they form the core of the upgrade request.
The Client's Secret Key
Another vital header from the client is Sec-WebSocket-Key.
- It's a 16-byte random value, encoded in Base64.
- It acts as a unique, unpredictable "nonce" (number used once) for each handshake.
- The server uses this key to prove it understands the WebSocket protocol and to prevent certain types of caching or proxy issues.
Protocol Version Check
The Sec-WebSocket-Version header is straightforward but important.
It tells the server which version of the WebSocket protocol the client is using. Currently, the standard version is 13.
This ensures both client and server speak the same "dialect" of the WebSocket language, guaranteeing compatibility.
Server Responds: 101 Switching Protocols
If the server supports WebSockets and agrees to the upgrade, it sends a special HTTP response back to the client.
The most important part of this response is the HTTP status code 101: Switching Protocols. This code explicitly means the server is changing protocols as requested by the client.
Server's Confirmation Key
The server's response also includes key headers:
Upgrade: websocketandConnection: Upgrade: Mirroring the client, these confirm the server's agreement to upgrade.Sec-WebSocket-Accept: This is a hash generated by the server using the client'sSec-WebSocket-Keyplus a specific "magic string". It proves the server understood the key and is capable of WebSockets.
Handshake Key Check
You've learned about the important headers involved in the WebSocket handshake.
Which of the following headers is sent by the client to initiate the WebSocket upgrade, and contains a random, unique value?
Connection Upgraded & Ready!
Once the client receives and validates the server's 101 response with the correct Sec-WebSocket-Accept header, the HTTP handshake is complete!
The connection is now upgraded to a full-duplex WebSocket. Both client and server can send and receive data simultaneously over this persistent connection, enabling true real-time communication.
Perguntas Frequentes
A aula “Explicando o handshake do WebSocket” é grátis?
Sim — o texto completo de “Explicando o handshake do WebSocket” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de WebSockets & Realtime Systems Programming, atualize para CoddyKit PRO. O curso de WebSockets & Realtime Systems Programming inclui 4 aulas no total.
O que vou aprender em “Explicando o handshake do WebSocket”?
Analise o processo de handshake baseado em HTTP que atualiza uma conexão HTTP padrão para uma conexão WebSocket. Você pratica WebSockets & Realtime Systems Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar WebSockets & Realtime Systems Programming?
Nenhuma experiência prévia é necessária. WebSockets & Realtime Systems Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Explicando o handshake do WebSocket”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de WebSockets & Realtime Systems Programming?
Sim. Cada aula de WebSockets & Realtime Systems Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Explicando o handshake do WebSocket
- Enquadramento de dados e mensagens WebSocket
- Ciclo de vida e estados da conexão
- Subprotocolos, extensões e compressão