2025, Sep 30 19:00
How to View the WebSocket Handshake Payload in Python's websocket-client by Enabling Trace Early
Learn how to view the WebSocket handshake payload in Python's websocket-client: enableTrace at module level before connecting to capture and debug issues.
How to view the WebSocket handshake payload in Python's websocket client
When debugging a WebSocket integration, it is often necessary to see the handshake payload. If you are using the Python websocket library and attempt to enable tracing on an already created connection object, you will not capture the initial exchange.
Below is a minimal snippet that illustrates the issue: tracing is enabled after the connection is created, so the handshake is already gone by the time debug output is turned on. Tweaking logging alone will not surface the handshake either.
from websocket import create_connection as open_conn
link = open_conn("ws://your-websocket-url")
# Too late to see the handshake
link.enableTrace(True)
# Even with logging configured, the handshake won't show up retroactively
import logging
logging.basicConfig(
    format="%(asctime)s %(message)s",
    level=logging.DEBUG,
)
What is happening
The handshake is performed during the initial connect phase. Enabling trace output after the connection exists means the library has already completed that negotiation. As a result, there is nothing to display for the handshake. The tracing toggle needs to be activated before an instance is created and before any connection attempt takes place.
Call websocket.enableTrace(True) directly on the class instead of the instance. Documented here.
The fix
Turn on tracing at the module level before creating the client. This ensures that the library captures and prints the handshake payload from the very start.
import websocket as ws_mod
# Enable debug/trace output before creating any WebSocket object
ws_mod.enableTrace(True)
chan = ws_mod.WebSocket()
chan.connect("ws://echo.websocket.events/", origin="testing_websockets.com")
chan.send("Hello, Server")
print(chan.recv())
chan.close()
Why this matters
Handshake visibility is crucial when diagnosing connection errors, header issues, or origin-related problems. If tracing is enabled too late or only via logging configuration, the critical negotiation data never appears, which leads to guesswork instead of direct evidence.
Takeaways
To inspect the handshake payload with the Python websocket client, enable tracing on the module before creating or connecting a WebSocket object using websocket.enableTrace(True). Relying on logging setup alone or toggling debug output on an already established instance will not expose the initial handshake.
The article is based on a question from StackOverflow by intrigued_66 and an answer by 0ro2.