Master WebSocket: From Handshake to Real‑Time Communication in Python and JavaScript

This article explains the WebSocket protocol, compares it with traditional Ajax polling, shows client‑side JavaScript and server‑side Python implementations, details the handshake, frame parsing, and message framing, and highlights its suitability for real‑time applications.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master WebSocket: From Handshake to Real‑Time Communication in Python and JavaScript

What is WebSocket?

WebSocket is a standard protocol for bidirectional data transfer over TCP, independent of HTTP.

Traditional client‑server communication relied on Ajax polling or long‑polling, which caused high server load and latency.

WebSocket solves these issues by upgrading an HTTP connection to a persistent, full‑duplex channel, allowing the server to push data without repeated handshakes.

Client request example:

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==
Sec-WebSocket-Version: 13

Key headers Upgrade: websocket and Connection: Upgrade indicate a WebSocket handshake.

Server response example:

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

Explanation of status code 101, Sec‑WebSocket‑Accept, and Sec‑WebSocket‑Protocol.

Calculation of Sec‑WebSocket‑Accept: concatenate Sec‑WebSocket‑Key with the GUID 258EAFA5‑E914‑47DA‑95CA‑C5AB0DC85B11, compute the SHA‑1 hash, then Base64‑encode the result.

Client Implementation (JavaScript)

var ws = new WebSocket("ws://127.0.0.1:8001");
ws.onopen = function(){ console.log('WebSocket opened!'); };
ws.onmessage = function(message){ console.log('receive message: ' + message.data); };
ws.onerror = function(error){ console.log('Error: ' + error.name + error.number); };
ws.onclose = function(){ console.log('WebSocket closed!'); };

Server Implementation (Python)

Creating a listening socket, performing the handshake, and parsing frames.

def create_socket():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('127.0.0.1', 8001))
    sock.listen(5)
    while True:
        conn, addr = sock.accept()
        data = conn.recv(1024).decode()
        # parse headers, compute Sec‑WebSocket‑Accept, send handshake
        # start a thread to handle frames

Frame parsing extracts FIN, RSV, Opcode, Mask, Payload length, and payload data, applying the masking key when present.

def read_msg(data):
    msg_len = data[1] & 127
    if msg_len == 126:
        mask = data[4:8]; content = data[8:]
    elif msg_len == 127:
        mask = data[10:14]; content = data[14:]
    else:
        mask = data[2:6]; content = data[6:]
    raw = ''.join(chr(b ^ mask[i % 4]) for i, b in enumerate(content))
    return raw

Sending frames uses the struct module to build the header and payload.

def write_msg(message):
    data = struct.pack('B', 129)  # FIN=1, opcode=1 (text)
    msg_len = len(message)
    if msg_len <= 125:
        data += struct.pack('B', msg_len)
    elif msg_len <= 65535:
        data += struct.pack('!BH', 126, msg_len)
    else:
        data += struct.pack('!BQ', 127, msg_len)
    data += message.encode('utf-8')
    return data

Conclusion

WebSocket provides true bidirectional communication, ideal for real‑time applications such as chat, live feeds, multiplayer games, collaborative editing, and video conferencing, outperforming traditional Ajax polling.

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.

BackendJavaScriptWebSocketprotocolreal-time communicationHandshake
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.