Master WebSocket Basics: Handshake, Protocol, and a Live JavaScript Demo
This tutorial explains the WebSocket protocol, shows the exact client handshake request and server response, and provides a concise JavaScript example that opens a connection, sends a message, receives a reply, and closes the socket, illustrating real‑time full‑duplex communication.
What is WebSocket
WebSocket is a communication protocol that enables full‑duplex communication over a single TCP connection. It simplifies data exchange between client and server, allowing the server to push data to the client without repeated requests. After a one‑time handshake, a persistent, bidirectional channel is established.
Client Request
GET /chat HTTP/1.1
Host: wss.tinywan.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: //example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13Server Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chatSimple Client Example
var ws = new WebSocket("wss://echo.websocket.org");
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
ws.onmessage = function(evt) {
console.log("Received Message: " + evt.data);
ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
