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.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Master WebSocket Basics: Handshake, Protocol, and a Live JavaScript Demo

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: 13

Server Response

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

Simple 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.");
};
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Real-TimeJavaScriptWebSocketprotocol
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.