- Notifications
You must be signed in to change notification settings - Fork775
WebSocket client for Python
License
websocket-client/websocket-client
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
websocket-client is a WebSocket client for Python. It provides accessto low level APIs for WebSockets. websocket-client implements versionhybi-13of the WebSocket protocol. This client does not currently support thepermessage-deflate extension fromRFC 7692.
This project's documentation can be found athttps://websocket-client.readthedocs.io/
Please see thecontribution guidelines
You can usepip install websocket-client
to install, orpip install -e .
to install from a local copy of the code. This module is tested on Python 3.9+.
There are several optional dependencies that can be installed to enablespecific websocket-client features.
- To install
python-socks
for proxy usage andwsaccel
for a minor performance boost, use:pip install websocket-client[optional]
- To install
websockets
to run unit tests using the local echo server, use:pip install websocket-client[test]
- To install
Sphinx
andsphinx_rtd_theme
to build project documentation, use:pip install websocket-client[docs]
While not a strict dependency,relis useful when usingrun_forever
with automatic reconnect. Install rel withpip install rel
.
Footnote: Some shells, such as zsh, require you to escape the[
and]
characters with a\
.
Check out the documentation's FAQ for additional guidelines:https://websocket-client.readthedocs.io/en/latest/faq.html
Known issues with this library include lack of WebSocket Compressionsupport (RFC 7692) andminimal threading documentation/support.
Thesend
andvalidate_utf8
methods can sometimes be bottleneck.You can disable UTF8 validation in this library (and receive aperformance enhancement) with theskip_utf8_validation
parameter.If you want to get better performance, install wsaccel. Whilewebsocket-client does not depend on wsaccel, it will be used ifavailable. wsaccel doubles the speed of UTF8 validation andoffers a very minor 10% performance boost when masking thepayload data as part of thesend
process. Numpy used tobe a suggested performance enhancement alternative, butissue #687found it didn't help.
Many more examples are found in theexamples documentation.
Most real-world WebSockets situations involve longer-lived connections.The WebSocketApprun_forever
loop will automatically try to reconnectto an open WebSocket connection when a networkconnection is lost if it is provided with:
- a
dispatcher
argument (async dispatcher like rel or pyevent) - a non-zero
reconnect
argument (delay between disconnection and attempted reconnection)
run_forever
provides a variety of event-based connection controlsusing callbacks likeon_message
andon_error
.run_forever
does not automatically reconnect if the servercloses the WebSocket gracefully (returninga standard websocket close code).This is the logic behind the decision.Customizing behavior when the server closesthe WebSocket should be handled in theon_close
callback.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()
This is if you want to communicate a short message and disconnectimmediately when done. For example, if you want to confirm that a WebSocketserver 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()
About
WebSocket client for Python
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.