Package: websocket-client
websocket-clientwebsocket-client is a WebSocket client for Python. It provides access
to low level APIs for WebSockets. websocket-client implements versionhybi-13of the WebSocket protocol. This client does not currently support the
permessage-deflate extension fromRFC 7692.DocumentationThis project's documentation can be found athttps://websocket-client.readthedocs.io/ContributingPlease see thecontribution guidelinesInstallationYou can use eitherpython3 setup.py installorpip3 install websocket-clientto install. This module is tested on Python 3.8+.There are several optional dependencies that can be installed to enable
specific websocket-client features.To installpython-socksfor proxy usage andwsaccelfor a minor performance boost, use:pip3 install websocket-client[optional]To installwebsocketsto run unit tests using the local echo server, use:pip3 install websocket-client[test]To installSphinxandsphinx_rtd_themeto build project documentation, use:pip3 install websocket-client[docs]While not a strict dependency,relis useful when usingrun_foreverwith automatic reconnect. Install rel withpip3 install rel.Footnote: Some shells, such as zsh, require you to escape the[and]characters with a\.Usage TipsCheck out the documentation's FAQ for additional guidelines:https://websocket-client.readthedocs.io/en/latest/faq.htmlKnown issues with this library include lack of WebSocket Compression
support (RFC 7692) andminimal threading documentation/support.PerformanceThesendandvalidate_utf8methods can sometimes be bottleneck.
You can disable UTF8 validation in this library (and receive a
performance enhancement) with theskip_utf8_validationparameter.
If you want to get better performance, install wsaccel. While
websocket-client does not depend on wsaccel, it will be used if
available. wsaccel doubles the speed of UTF8 validation and
offers a very minor 10% performance boost when masking the
payload data as part of thesendprocess. Numpy used to
be a suggested performance enhancement alternative, butissue #687found it didn't help.ExamplesMany more examples are found in theexamples documentation.Long-lived ConnectionMost real-world WebSockets situations involve longer-lived connections.
The WebSocketApprun_foreverloop will automatically try to reconnect
to an open WebSocket connection when a network
connection is lost if it is provided with:adispatcherargument (async dispatcher like rel or pyevent)a non-zeroreconnectargument (delay between disconnection and attempted reconnection)run_foreverprovides a variety of event-based connection controls
using callbacks likeon_messageandon_error.run_foreverdoes not automatically reconnectif the server
closes the WebSocket gracefully (returninga standard websocket close code).This is the logicbehind the decision.
Customizing behavior when the server closes
the WebSocket should be handled in theon_closecallback.
This example usesrelfor the dispatcher to provide automatic reconnection.importwebsocketimport_threadimporttimeimportreldefon_message(ws,message):print(message)defon_error(ws,error):print(error)defon_close(ws,close_status_code,close_msg):print("### closed ###")defon_open(ws):print("Opened connection")if__name__=="__main__":websocket.enableTrace(True)ws=websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",on_open=on_open,on_message=on_message,on_error=on_error,on_close=on_close)ws.run_forever(dispatcher=rel,reconnect=5)# Set dispatcher to automatic reconnection, 5 second reconnect delay if connection closed unexpectedlyrel.signal(2,rel.abort)# Keyboard Interruptrel.dispatch()Short-lived ConnectionThis is if you want to communicate a short message and disconnect
immediately when done. For example, if you want to confirm that a WebSocket
server is running and responds properly to a specific request.fromwebsocketimportcreate_connectionws=create_connection("ws://echo.websocket.events/")print(ws.recv())print("Sending 'Hello, World'...")ws.send("Hello, World")print("Sent")print("Receiving...")result=ws.recv()print("Received '%s'"%result)ws.close()