Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

WebSocket client for Python

License

NotificationsYou must be signed in to change notification settings

websocket-client/websocket-client

Repository files navigation

docsBuild StatuscodecovPyPI DownloadsPyPI versionLicenseCode style: black

websocket-client

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.

Documentation

This project's documentation can be found athttps://websocket-client.readthedocs.io/

Contributing

Please see thecontribution guidelines

Installation

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 installpython-socks for proxy usage andwsaccel for a minor performance boost, use:pip install websocket-client[optional]
  • To installwebsockets to run unit tests using the local echo server, use:pip install websocket-client[test]
  • To installSphinx 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\.

Usage Tips

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.

Performance

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.

Examples

Many more examples are found in theexamples documentation.

Long-lived Connection

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:

  • adispatcher argument (async dispatcher like rel or pyevent)
  • a non-zeroreconnect argument (delay between disconnection and attempted reconnection)

run_forever provides a variety of event-based connection controlsusing callbacks likeon_message andon_error.run_foreverdoes 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()

Short-lived Connection

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()

[8]ページ先頭

©2009-2025 Movatter.jp