Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python WebSocket: How to Print Handshake?

Learn how to inspect WebSocket handshake in Python using the websocket-client library. Discover the right way to enable trace output.
Python WebSocket handshake debug illustration with HTTP headers and trace logs Python WebSocket handshake debug illustration with HTTP headers and trace logs
  • 📡 Over 60% of real-time apps use WebSocket. This shows how important it is for web communication today.
  • 🧐 Looking at the WebSocket handshake helps find connection failures, protocol problems, and server setup mistakes.
  • 🔍 Turning on enableTrace() in Python’s websocket-client shows handshake headers and status codes right away.
  • 🔑 A successful handshake always has HTTP 101 and a good Sec-WebSocket-Accept key from the server.
  • 🔐 Leaving tracing on in a live system can show private information. So, turn it off after you finish debugging.

Introduction

WebSocket connections make many real-time apps work. But when there's a problem during development, checking the first handshake is often the quickest way to find what caused it. This article explains how to use Python's websocket-client library. It shows you how to print and look at the WebSocket handshake process. This helps you fix connection problems and better understand how clients and servers talk to each other at a basic level.


What is a WebSocket Handshake?

Before you can use a WebSocket connection to send and get data right away, the client and server do a handshake. This is a required talk using HTTP. It changes the protocol from HTTP to WebSocket. This allows a steady, two-way talk over one TCP connection.

The client starts the handshake by sending a special HTTP request. It includes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Upgrade: websocket: This shows the client wants to change the connection.
  • Connection: Upgrade: This confirms the request to switch protocols.
  • Sec-WebSocket-Key: This is a random value, encoded in base64, that is only for this client.
  • Sec-WebSocket-Version: 13: This says what WebSocket protocol version is used.

If the server accepts, it replies with:

  • HTTP/1.1 101 Switching Protocols: This shows the protocol switch worked.
  • Upgrade: websocket and Connection: Upgrade: This agrees to the change.
  • Sec-WebSocket-Accept: This is a confirmation code made from the client’s key.

✅ This process follows the standard in [RFC 6455]. This makes sure different servers and clients can work together.

Why the Handshake Matters

If anything changes from what should happen, real-time apps will show problems on the user's screen or blank screens. By checking the handshake, developers can find out if:

  • The server replied with an error or an incomplete header.
  • The request has wrong settings.
  • Network devices (like proxies or firewalls) changed the request.

Why Use the Python websocket-client Library?

Python has several WebSocket libraries, like aiohttp and websockets. But the websocket-client library is best for setting up and checking WebSocket handshakes.

Main good points:

  • 🛠️ Its synchronous API is good for simple tests.
  • 🧪 It has built-in debugging through enableTrace.
  • 📦 It's lightweight and needs few other tools.
  • 🔧 It gives direct control over headers, URLs, and frames.

📊 A 2022 survey by JetBrains and PSF shows that over 22% of Python users use WebSocket libraries. They use them for things like messaging, games, and sending data streams.

To install:

pip install websocket-client

This gives you tools that work well for client WebSocket tasks.


Basic Setup: Connecting to a WebSocket Server

Before you can check the handshake, you need a working client connection. Here is a basic setup that shows how to make a connection:

import websocket

ws = websocket.WebSocket()
ws.connect("wss://echo.websocket.events")
print("Connected to WebSocket server.")
ws.close()

This connects to a public echo WebSocket server. You will see that this will not show any handshake details unless tracing is turned on.


Enable Trace to View the Handshake

To see the full details of the handshake, turn on Python's debugging tool using:

websocket.enableTrace(True)

This function sends detailed output, like headers, responses, and frame data, to stdout. The logs usually show:

  • The full HTTP request header.
  • The HTTP response headers received.
  • Connection status codes (for example, 101, 403, 404).
  • Errors, lost frames, and close codes.

📌 As the websocket-client documentation says, this logs both incoming and outgoing traffic. So, it acts like a built-in sniffer that works well for developers.


Full Example: Printing the WebSocket Handshake

Here is a complete script that uses enableTrace(True) and handles WebSocket events:

import websocket

websocket.enableTrace(True)

def on_open(wsapp):
    print("Connection opened")

def on_message(wsapp, message):
    print("Received message:", message)

def on_error(wsapp, error):
    print("Error:", error)

def on_close(wsapp, close_status_code, close_msg):
    print("Connection closed")

ws = websocket.WebSocketApp("wss://echo.websocket.events",
                            on_open=on_open,
                            on_message=on_message,
                            on_error=on_error,
                            on_close=on_close)
ws.run_forever()

When you run this, you will see detailed output like this:

--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: echo.websocket.events
Origin: http://echo.websocket.events
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
-----------------------

Understanding the Handshake Output

Each part of the handshake can tell you something important. Here is how to understand it:

  • Client Side:

    • Sec-WebSocket-Key: This is a random string used to start checking security.
    • Origin: This is very important for browser WebSocket requests, showing where they came from.
    • Host: This is the target domain and port of the server.
  • Server Response:

    • HTTP/1.1 101: This shows the request to switch protocols worked.
    • Sec-WebSocket-Accept: This is made from Sec-WebSocket-Key and a special string, as per RFC 6455. It needs to match what is expected for the handshake to finish.

If any of these headers do not match or are missing, it usually means there are setup problems on either side.


Common Debugging Use Cases

You can use WebSocket trace logs to:

  • 🛑 Find problems with login and headers, like missing cookies or tokens.
  • 🔌 See if proxy servers caused upgrade failures.
  • 📡 Compare good and bad handshake replies from different setups, like testing vs. live.
  • 🔂 Fix reconnection code by looking at server close codes and messages.

🧠 A 2022 report from Statista says that 60% of today's real-time apps use WebSocket. This shows that a healthy handshake is key to stable apps.


Troubleshooting Common Errors Using Handshake Details

The trace output is very helpful for finding common handshake errors:

Status Code Meaning Likely Cause
404 Not Found Wrong path in the client's URL
403 Forbidden Login failed or wrong source
500 Internal Server Error Problem with the server's code
Sec-WebSocket-Accept mismatch Client or a middle program changed headers
SSL/TLS failure WSS vs. WS problem or bad security certificate

You can get more hints from WebSocket close codes like 1006 (unexpected close) or 1011 (server error). These codes give developers clear details.


Security Precautions: Don't Leave Tracing On

Debugging is very important. But enableTrace(True) should never stay on in live systems. Here's why:

  • 🔓 Trace logs might record login headers, JWTs, or API keys.
  • 🕵️ While Sec-WebSocket-Key values are not really private, seeing them could help someone figure out how things work.
  • 📄 Debug logs can fill up live system storage or get into central log systems.

✅ It's best to set up your system to turn tracing on for development and testing, and off by default for live use.


Optional: Send Trace Logs to a File

To keep handshake information, you can send trace logs to a file:

import websocket
import logging

websocket.enableTrace(True)

logging.basicConfig(filename="websocket_debug.log",
                    level=logging.DEBUG,
                    format='%(asctime)s - %(message)s')

With this setup:

  • All WebSocket actions, like handshakes, messages, and errors, go to websocket_debug.log.
  • Development teams can save logs to look at later or for quality assurance tests.

Test with Public WebSocket Servers

To try things out, use these public WebSocket endpoints:

Test Server Description
wss://echo.websocket.events Sends back any message you send
wss://ws.ifelse.io Sends back random replies
wss://demos.kaazing.com/echo A good echo service for businesses

These basic echo servers give you a safe place to test handshake results and how the protocol acts.

🚨 Note: Free servers may limit how much you can use them. So, check if the handshake works before you use it.


Alternatives & Deeper Debugging

The websocket-client is good for simple cases. But bigger projects might find these helpful:

  • websockets: This is a library for async code. It handles many WebSockets in asyncio apps.
  • aiohttp: This is a client/server tool for both HTTP and WebSocket apps. These apps need to control state.
  • DevTools Integration:
    • Chrome and Firefox let you look at WebSocket traffic under DevTools > Network Tab > WS.
  • Wireshark or Fiddler:
    • These tools watch raw TCP data and TLS decoding. You can use them to check handshakes in detail.

By using these tools with Python scripts, teams can see all live WebSocket traffic.


Real-World Integration and Debugging

Seeing the handshake is very important for:

  • 🧑‍💼 Business Messaging: Making sure employee dashboards update right away.
  • 📈 Financial Platforms: Allowing secure live stock data to stream.
  • 🎮 Gaming Apps: Finding lost data packets and errors in live state updates.
  • 🧪 QA/DevOps Pipelines: Checking how live servers upgrade before products are released.

Putting trace tests into CI/CD helps find handshake problems sooner.


Best Practices for WebSocket Debugging

Quick tips for good debugging:

  • ✅ Use enableTrace(True) only on testing setups.
  • ✅ Make sure you get HTTP 101 before sending any data.
  • ✅ Save logs for failed tests. And then delete old logs from time to time.
  • ✅ Check handshake headers in automated tests.
  • ✅ Check TLS certificates again and make sure you are using WS or WSS correctly.

Time to Debug Smarter

WebSocket handshakes are often not seen. But they are key to steady, fast communication. By turning on tracing in Python with websocket-client, developers get a clear view of this protocol step. Whether you are fixing a connection that breaks sometimes or checking how a new server upgrade acts, knowing how to check the handshake helps you a lot.


Citations

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading