pax_global_header00006660000000000000000000000064145327424000014513gustar00rootroot0000000000000052 comment=85de6c7e14058ca37224303d5468a560413a6205 websocket-client-1.7.0/000077500000000000000000000000001453274240000147625ustar00rootroot00000000000000websocket-client-1.7.0/.coveragerc000066400000000000000000000004411453274240000171020ustar00rootroot00000000000000[run] branch = True source = websocket-client omit = websocket/tests/*,websocket/_wsdump.py [report] exclude_lines = if self.debug: pragma: no cover raise NotImplementedError if __name__ == .__main__.: ignore_errors = True include = websocket/* omit = websocket/tests/* websocket-client-1.7.0/.gitattributes000066400000000000000000000010611453274240000176530ustar00rootroot00000000000000# Basic Python .gitattributes from https://github.com/alexkaratarakis/gitattributes # Source files # ============ *.pxd text diff=python *.py text diff=python *.py3 text diff=python *.pyw text diff=python *.pyx text diff=python *.pyz text diff=python *.pyi text diff=python # Binary files # ============ *.db binary *.p binary *.pkl binary *.pickle binary *.pyc binary export-ignore *.pyo binary export-ignore *.pyd binary # compliance files # ================ compliance/* linguist-vendored *.sh linguist-vendored websocket-client-1.7.0/.github/000077500000000000000000000000001453274240000163225ustar00rootroot00000000000000websocket-client-1.7.0/.github/workflows/000077500000000000000000000000001453274240000203575ustar00rootroot00000000000000websocket-client-1.7.0/.github/workflows/build.yml000066400000000000000000000025111453274240000222000ustar00rootroot00000000000000name: build and test on: [push, pull_request] env: FORCE_COLOR: 1 jobs: build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: python-version: ['3.8', '3.9', '3.10', '3.11', '3.12'] os: [ubuntu-latest] steps: - name: Check out source repository uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} environment uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} allow-prereleases: true - name: Run local websockets echo server on port ${{ env.LOCAL_WS_SERVER_PORT }} (code is for Python 3.7+) run: | pip3 install -U websockets asyncio python3 websocket/tests/echo-server.py & - name: Install build tools and print setuptools version run: | pip3 install -U pip setuptools wheel readme_renderer twine pytest python-socks python3 -c "import setuptools; print('Setup tools version'); print(setuptools.__version__)" - name: Run tests run: | pytest websocket/tests -v -rP env: TEST_WITH_INTERNET: 1 LOCAL_WS_SERVER_PORT: 8765 - name: Run distutils and confirm build of websocket-client run: | python3 setup.py sdist twine check dist/* websocket-client-1.7.0/.github/workflows/codecoverage.yml000066400000000000000000000045641453274240000235410ustar00rootroot00000000000000name: Code Coverage on: [push, pull_request] jobs: code-coverage: runs-on: ubuntu-latest steps: - name: Check out source repository uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} environment uses: actions/setup-python@v4 with: python-version: "3.10" - name: Run local websockets echo server on port ${{ env.LOCAL_WS_SERVER_PORT }} run: | pip3 install -U websockets asyncio python3 websocket/tests/echo-server.py & - name: Run test cases without internet or option dependencies to verify no offline test failures and verify optional dependencies are optional run: | pip3 install coverage pytest pytest-cov setuptools python3 -c "import setuptools; print('Setup tools version'); print(setuptools.__version__)" python3 setup.py install pytest -vrP --cov=websocket websocket/tests --cov-config=.coveragerc coverage report - name: Install wsaccel and python-socks, then run all test cases for coverage collection run: | pip3 install wsaccel python-socks pytest -vrP --cov=websocket websocket/tests --cov-config=.coveragerc --cov-append coverage report env: TEST_WITH_INTERNET: 1 LOCAL_WS_SERVER_PORT: 8765 - name: Run SSL test with extra environment variable and create report run: | ls $WEBSOCKET_CLIENT_CA_BUNDLE python3 -c "import ssl; print(ssl.get_default_verify_paths().capath)" pytest -vrP --cov=websocket websocket/tests --cov-config=.coveragerc --cov-append -k "testSSLopt" coverage report -m env: TEST_WITH_INTERNET: 1 LOCAL_WS_SERVER_PORT: 8765 WEBSOCKET_CLIENT_CA_BUNDLE: "/usr/lib/ssl/certs" - name: Run SSL test with extra environment variable and create report run: | python3 -c "import ssl; print(ssl.get_default_verify_paths().capath)" pytest -vrP --cov=websocket websocket/tests --cov-config=.coveragerc --cov-append -k "testSSLopt" coverage xml env: TEST_WITH_INTERNET: 1 LOCAL_WS_SERVER_PORT: 8765 WEBSOCKET_CLIENT_CA_BUNDLE: "/usr/lib/ssl/certs/Baltimore_CyberTrust_Root.pem" - name: Submit code coverage report to Codecov.io uses: codecov/codecov-action@v3 websocket-client-1.7.0/.github/workflows/doctest.yml000066400000000000000000000010661453274240000225520ustar00rootroot00000000000000name: Run doctest on Sphinx docs on: [push, pull_request] jobs: run-doctest: runs-on: ubuntu-latest name: doctest check steps: - name: Check out source repository uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} environment uses: actions/setup-python@v4 with: python-version: "3.11" - name: Run pytest with doctest args run: | pip3 install pytest 'websocket-client[docs]' rel pytest ./docs/source -v --doctest-glob="*.rst" --doctest-modules websocket-client-1.7.0/.github/workflows/lint-black.yml000066400000000000000000000005171453274240000231250ustar00rootroot00000000000000name: Linting with black on: [push, pull_request] jobs: black-lint: runs-on: ubuntu-latest name: black linting steps: - name: Check out source repository uses: actions/checkout@v3 - name: Run black linting uses: psf/black@stable with: options: "--check" src: "." websocket-client-1.7.0/.github/workflows/lint-flake8.yml000066400000000000000000000013241453274240000232200ustar00rootroot00000000000000name: Linting with flake8 on: [push, pull_request] jobs: flake8-lint: runs-on: ubuntu-latest name: flake8 linting steps: - name: Check out source repository uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} environment uses: actions/setup-python@v4 with: python-version: "3.11" - name: Perform mandatory flake8 linting run: | pip3 install flake8 flake8 --version flake8 . --show-source --statistics --count --ignore E231,E241,E501,E722,E741,F401,F403,F405,W503,W504 - name: Perform optional exit-zero flake8 linting run: | flake8 . --exit-zero --statistics --count websocket-client-1.7.0/.gitignore000066400000000000000000000003261453274240000167530ustar00rootroot00000000000000*.pyc *~ *\# .\#* build .build/ dist *.egg-info .cache/ compliance/reports/ .eggs .vscode # venv venv/ .venv/ .env/ # PyCharm .idea/ # Sphinx documentation docs/build/ # Code coverage .coverage coverage.xml websocket-client-1.7.0/.readthedocs.yml000066400000000000000000000007741453274240000200600ustar00rootroot00000000000000# .readthedocs.yml # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Build documentation in the docs/ directory with Sphinx sphinx: configuration: docs/source/conf.py # Optionally build your docs in additional formats such as PDF formats: - pdf # Optionally set the version of Python and requirements required to build your docs python: version: 3.8 install: - requirements: docs/source/requirements.txt websocket-client-1.7.0/CONTRIBUTING.md000066400000000000000000000063661453274240000172260ustar00rootroot00000000000000# Contributing Hello :wave: and thank you for contributing! :tada: Before you contribute, please take a minute to review the contribution process based on what you want to do. ## I got an error or I have a question Great! We are happy to help. Before you ask your question, please check if your question can be answered from the following 5 steps: - [ ] The [project documentation examples](https://websocket-client.readthedocs.io/en/latest/examples.html) - [ ] The [project documentation FAQ](https://websocket-client.readthedocs.io/en/latest/faq.html) - [ ] Search for your question in [old existing issues](https://github.com/websocket-client/websocket-client/issues) - [ ] If you encountered an error message, try googling the error message and see if you find an answer - [ ] Check if the same issue exists if you uninstall the websocket-client library on your system (using `pip uninstall websocket-client` or maybe `pip3 uninstall websocket-client`) and install the [latest master branch](https://github.com/websocket-client/websocket-client) directly from GitHub by using `python setup.py install` (see [installation info](https://github.com/websocket-client/websocket-client#installation)) If you did not get your question answered from these 5 steps, then please open a new issue and ask your question! When you explain your problem, please: - [ ] [Enable the tracing feature](https://websocket-client.readthedocs.io/en/latest/examples.html#debug-and-logging-options) and include the entire debug trace of your connection process in the issue - [ ] Provide a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) program to allow other users to recreate and demonstrate the error - [ ] Add an explanation for what you are trying to accomplish. If you can provide your code (or example code) in the issue, this helps a lot! ## I have a suggestion or idea Great! Please make a new issue an explain your idea, but first do a quick search in [old existing issues](https://github.com/websocket-client/websocket-client/issues) to see if someone already proposed the same idea. ## I want to contribute code Great! In your pull request (PR), please explain: 1. What is the problem with the current code 2. How your changes make it better 3. Provide some example code that can allow someone else to recreate the problem with the current code and test your solution (if possible to recreate). ## I want to contribute documentation Great! To edit the [project documentation](https://websocket-client.readthedocs.io), it is recommended that you install Sphinx and build the updated documentation locally before submitting your edits. The Sphinx dependencies can be installed by navigating to the `docs/source` directory and running `pip3 install -r requirements.txt`. To build a new version of the documentation, change directories (or `cd`) to the `docs/` directory and run `make clean html`. Any build warnings or errors will be displayed in your terminal, and the new documentation will then be available in the `docs/build/html/` directory. You may also find the [Sphinx documentation style guide](https://documentation-style-guide-sphinx.readthedocs.io/en/latest/style-guide.html) useful when editing reStructuredText (reST), which is quite different from Markdown. websocket-client-1.7.0/ChangeLog000066400000000000000000000440341453274240000165410ustar00rootroot00000000000000ChangeLog ============ - 1.7.0 - Renamed `mask` variable in ABNF to prevent name collision with `mask()` function (9b51f73) - Fixed old http import of HTTPStatus in _handshake.py (9b51f73) - Add `send_text()` and `send_bytes()` to _app.py (#953) - Improved typehint support (#953, 9b51f73, 8b73d00) - General readability improvements, made all string concatenations use f-strings (#909, 780584f, 3eabc6e) - Applied black formatting style to code (da7f286) - 1.6.4 - Fix #952, add support for HTTP 307 and 308 redirect codes (69468ad) - 1.6.3 - Fix type hints issues (#949) - Add support for Python beta release 3.12 in CI (#946) - Add maintainer email in setup.py (3d464fc) - 1.6.2 - Add support for SSLKEYLOGFILE environment variable (#943) - Add support for callable header arguments (#932) - Change handling of proxy environment variables, is_secure set to true now prevents http_proxy from getting used (#929) - 1.6.1 - Fix Dispatcher keyboard interrupt. Should solve reconnect loop with rel (#924) - 1.6.0 - Fix teardown issue when ping thread is not properly ended (#918) - Fix double ping wait time on first ping (#912) - Minor type hints improvements (eda6724, 54b3013) - 1.5.3 - Add logic to avoid error in the case where content-length header does not exist, bug introduced in 1.5.2 (#911) - Fix wsdump.py script typing, bug introduced in 1.5.2 (#914) - 1.5.2 - Add type hints (#908) - Fix pytype errors (#906) - Fix args passed to logging function (#898) - Standardize PEP 3101 formatting (c6a445f) - Add more verbose exception for unsuccessful handshake for #900 (f85ae1f) - 1.5.1 - Fix logic bug that can cause disconnects (#893) - 1.5.0 - Refactor and improve ping/pong logic to resolve several issues, including an infinite loop issue during reconnect (#862) - Fix issue where `skip_utf8_validation = True` is ignored (#886) - Fix issue where sslopt `is_ssl` is ignored (#875) - Downgrade "websocket connected" message from logging.warning to logging.info (#888) - Update github actions to newer versions (669fe1b) - 1.4.2 - create_dispatcher is determined by URL ws/wss, NOT by presence of sslopt args, to maintain consistency (#875) - Remove redundant key generation line (#864) - Updated docs to fix old links and updated CI to include Python 3.11 - 1.4.1 - Fix stack growth bug when `run_forever` reconnects (#854) - Add doctest CI for sphinx docs code examples (d150099) - General docs improvements - 1.4.0 - Fix automatic reconnect with `run_forever` (#838) - Allow a timeout to be set when using a proxy (#842) - 1.3.3 - Fix unclosed socket error (#826) - Update header dict access (#818) - Add utf8 workaround to docs (fc9ee9f) - 1.3.2 - Add support for pre-initialized stream socket in new WebSocketApp (#804) - Remove rel.saferead() in examples (f0bf03d) - Increase scope of linting checks (dca4022) - Start adding type hints (a8a4099) - 1.3.1 - Fix 10 year old bug and improve dispatcher handling for run_forever (#795) - Fix run_forever to never return None, only return True or False, and add two tests (#788) - Remove Python 3.6 support, EOL in Dec 2021 - 1.3.0 - BREAKING: Set Origin header to use https:// scheme when wss:// WebSocket URL is passed (#787) - Replace deprecated/broken WebSocket URLs with working ones (6ad5197) - Add documentation referencing rel for automatic reconnection with run_forever() - Add missing opcodes 1012, 1013 (#771) - Add errno.ENETUNREACH to improve error handling (da1b050) - Minor documentation improvements and typo fixes - 1.2.3 - Fix broken run_forever() functionality (#769) - 1.2.2 - Migrate wsdump script in setup.py from scripts to newer entry_points (#763) - Add support for ssl.SSLContext for arbitrary SSL parameters (#762) - Remove keep_running variable (#752) - Remove HAVE_CONTEXT_CHECK_HOSTNAME variable (dac1692) - Replace deprecated ssl.PROTOCOL_TLS with ssl.PROTOCOL_TLS_CLIENT (#760) - Simplify code and improve Python 3 support (#751, #750, #746) - Fill default license template fields (#748) - Update CI tests - Improve documentation (#732, #733, #734, #737, #766, #768) - 1.2.1 - Fix python-socks dependency issue mentioned in #728 - Replace echo.websocket.org with a local websockets echo server for unit tests (4951de2) - 1.2.0 - Fix #697, #665: Transition from LGPL 2.1 license to Apache 2.0 license - Revert #417 and reimplement SOCKS proxy support with python-socks instead of PySocks (fbcbd43) - 1.1.1 - Fix #377: increase exception verbosity in _app.py callback exception - Fix #717: race condition during connection close - Fix #722: improve handling where credentials include symbols like @ - Fix #711: improve handling if ssl is None - 1.1.0 - Set enable_multithread to True by default (beb135a) - Performance improvement in _mask() function (287970e, #433) - Performance improvement in recv_strict() function (60e4711, #255) - Performance improvement by removing numpy-related code (a462d45) - Support uppercase no_proxy, http_proxy, https_proxy env vars (150df4f, #700) - Add sslopt 'server_hostname' support (#698) - Replace deprecated ssl.PROTOCOL_SSLv23 with ssl.PROTOCOL_TLS (494564f) - Update documentation, README (7c9d604, #704) - 1.0.1 - Fix exception handling bug #694 - 1.0.0 - Removed Python 2 code, now only Python 3 compatible (d45343b, b7c5733, ff67af8) - Use semver for release versions, unlike breaking release 0.58.0 (#669) - Enhance enableTrace output (13e83b4) - Improve unit tests to over 80% code coverage (1679ab0, a00dd2d, etc.) - Fix old _app.py close status code bug (resulted in on_close() requiring 3 args) (#686) - Replace select import with selectors (#568) - 0.59.0 - Last main release to support Python 2 - Fix Python 2 urlparse scheme (#332) - Add support for headers with multiple values (#627) - Add debug support for reserved custom status codes (#639) - Allow multiple Set-Cookie: headers (#649) - Simplified cookie sorting (#662) - Add no_proxy support (#671) - Add Host header to HTTP proxy request (#677) - Improve PEP8 style compliance (dc3f5c4) - 0.58.0 - Fix README typos (#659) - Create README.md from README.rst (#655) - Capitalize 'Upgrade' in 'Connection: Upgrade' (#605) - Add Python 3.8 and 3.9 CI support (#596) - Replace deprecated `thread.isAlive` with `thread.is_alive` (#594) - Revert to LGPL v2.1 license (#526) - Add code coverage CI testing (#663) - Properly revert callback (#442) - Replace TravisCI with GitHub Actions (36e32c7) - Create Sphinx readthedocs.io documentation (aace06b) - 0.57.0 - wsdump: Fix --headers option (#589) - Fix getting 400 bad request with long proxy authorization string (#587) - Fix for errors that occur when closing websocket from another thread (#586) - avoid calling repr(data) if tracing is not enabled (#584) - Fixed typo (#579) - Create dummy `ssl` object (#577) - Show compressed text messages in wsdump.py (#576) - Resolve issue opening socket to intranet on Windows 10 with no proxy settings but behind proxy (#573) - Expose http connection header to user (#566) - Improve the readability of HTTP status codes. (#553) - fix the compatible issue with gevent+dnspython (#547) - v should be checked for empty string before splitting it (#539) - _handshake: hasattr checks on six before accessing the values (#533) - 0.56.0 - Don't retry sockets with timeout set to 0(#536) - 0.55.0 - Add response headers in WebSocketBadStatusException (#501) - Manually assigning WebSocket-Version (#506) - SSL socket handling fix (#474) - Let setup.py use the same license as LICENSE file (#517) - Ensure that "timeout" is passed down, when calling WebSocket.connect() (#513) - Retry connect on "Interrupted system call" (#528) - 0.54.0 - Change license from LGPL to BSD. - Status return for WebSocketApp.run_forever() (#492) - Handle redirects in handshake (#491) - Make proxy_type option available in WebSocketApp.run_forever() (#486) - Fix typo in supress_origin (#485) - WebSocketApp's on_close never emits status code or reason (#479) - 0.53.0 - on_open() missing 1 required positional argument: 'ws' (#471) - 0.52.0 - fixed callback argument in _app.py (#468) - Fixing none compare bug in run_forever (#472) - Fix NoneType bug introduced by #386 fix (#476) - 0.51.0 - revert "WebSocketApp class to make it inheritable (#442)" because of breaking the compatibility - 0.50.0 - fixed pong before ping (#461) - pass proper arguments to method callbacks (#462) - 0.49.0 - WebSocketApp class to make it inheritable (#442) - Add option to disable sending the Origin header (#459) - Websocket.close() meaning of "close status: XXXXX" (#414) - Enable multithreading protection with ping_interval (#448) - reset WebsocketApp.sock (#450) - websocket.enableTrace not working (#455) - AttributeError: 'module' object has no attribute 'NullHandler' (#443) - WebSocketBadStatusException "not enough arguments for format string" (#454) - handshake should deal with None in headers (#432) - 0.48.0 - Add NullHandler to logger to fix python 2 issue. (#400) - Fix the issue that websocket status message may not present (#403) - Socket error not raised in nested try except in python2 (#408) - Load system default certificates if none are given (#415) - Fix waiting forever on ping/pong timeout (#411) - socks5 via pysocks support (#417) - v0.47.0 breaks ability to stop stream with `run_forever` (#410) - _http.py: fix windows proxy error due to socktype (#427) - 0.47.0 - Fix socket constructor in _open_socket to use all relevant variables from getaddrinfo. (#383) - .send() method is very slow (#340) - cross-platform aync multi-client solution (#375) - Fix detecting timeouts with SSL in recv (#387) - Fix WebSocketApp does not poll for data correctly when using SSL (#384) - Fix Infinite ping/pong timeouts in WebSocketApp.run_forever (#395) - Added status message when HTTP can't be upgraded to WS (#399) - 0.46.0 - fixed OSError on windows (#370) - fixed invalid character (#379) - 0.45.0 - change license to LGP v2.1 - allow reuse of WebsocketApp.run_forever (#365) - Update example for python3 (#360) - add lock to recv function (#356) - Parse close frame response correctly when reason present (#354) - Fix SSL: SSLV3_ALERT_HANDSHAKE_FAILURE on Debian Stretch (#353) - Wrap socket.gaierror with subclass of WebsocketException (#352) - Resolve a proxy issue and a connection error (#345) - Allow empty Host header value (#369) - Fix undefined variable (#347) - fix: getting a value with the key 'ca_certs' in sslopt dict (#326) - 0.44.0 -renames key in sslopt dict (#326) - 0.43.0 - Unknown kwarg 'ca_cert' when calling ssl wrap_socket() (#326) - Race condition in WebSocket ping/pong (#327) - 0.42.0 - Implement simple cookie jar(#292) - fix: when using pppoe redial will block.(#301) - Fix insecure_pythons list in setup.py(#304) - Support WEBSOCKET_CLIENT_CA_BUNDLE being directory(#307) - WebSocketPayloadException under high traffic and limited network connection(#306) - Not working --nocert parameter in wsdump.py(#315) - Avoid the app to block on close on certain systems (#320) - Fix warning is not defined. (#323) - 0.41.0 - move to repository to https://github.com/websocket-client/websocket-client.git - _send_ping warning fails due to missing reference in _logging.__all__ (#294) - 0.40.0 - Fix opcode -> op_code (#286) - 0.39.0 - Shuffled around example code (#256) - _send_ping graceful error handling (#262) - Allow closing WebSocketApp with status/reason/timeout (#265) - Support universal wheels (#267) - _url: Added subnet IP address matching in no_proxy host detection (#270) - fixed Incorrect encoding in continued messages python3 (#261) - Pass headers for websocket handshake (#271) - setup.py: Import `logging` before calling it. (#272) - Implemented close code 1014 (#273) - Support CA bundle specified by environment variable (#279) - Response header values should not be converted to lower case (#264) - 0.38.0 - Exclude port 443 from host http header (#248) - Cleanup code (#249) - Modify a code block directive in README (#250) - fixed ping/pong timeouet (#253) - 0.37.0 - fixed failure that `websocket.create_connection` does not accept `origin` as a parameter (#246 ) - 0.36.0 - added support for using custom connection class (#235) - use Named logger (#238) - implement ping/pong timeout (#241) - Corrects the syntax highlight code (#243) - fixed failure to join thread before it is started (#242) - 0.35.0 - Prints timings in console (#217) - use inspect.getfullargspec with Python 3.x (#219) - Check that exception message is actually a string before trying for substring check (#224) - Use pre-initialized stream socket (#226) - fixed TypeError: cafile, capath and cadata cannot be all omitted (#227) - 0.34.0 - Change import style (#203) - fix attribute error on the older python. (#215) - 0.33.0 - fixed timeout+ssl error handling bug on python 2.7.10 (#190) - add proxy support to wsdump.py (#194) - use wsaccel if available (#193) - add support for ssl cert chains to support client certs (#195) - fix string formatting in exception (#196) - fix typo in README.rst (#197) - introduce on_data callback to pass data type. (#198) - WebSocketBadStatusException for Handshake error (#199) - set close timeout (#192) - Map dict to headers list (#204) - support client certification (#207) - security improvement during handshake (#211) - improve logging of error from callback (#212) - 0.32.0 - fix http proxy bug (#189) - 0.31.0 - Avoid deprecated BaseException.message (#180) - Add travis builds (#182) - fixed wsdump to work with piped input (#183) - fixed output of wsdump.py with python3 (#185) - add raw mode to wsdump.py (#186) - 0.30.0 - fixed if client is behind proxy (#169) - support SNI for python 2.7.9+ and 3.2+ (#172) - update Host HTTP header by user. (#171) - fix typo for isEnabledFor (#173) - can set verify_mode to CERT_NONE when check_hostname is enabled.(#175) - make websockets iterable (#178) - 0.29.0 - fixed ssl socket bug - 0.28.0 - Fix erroneous argument shadowing(#168) - 0.27.0 - remove unittest2 requirements for python 2.6 (#156) - fixed subprotocol case during header validation (#158) - get response status and headers (#160) - fix out-of-memory due to fragmentation when receiving a very large frame(#163) - fix error if the payload data is nothing.(#166) - refactoring. - 0.26.0 - all WebSocketException provide message string (#152) - fixed tests fail when not connected to the network (#155) - Add command line options and handle closed socket to wsdump.py (#153) - 0.25.0 - fixed for Python 2.6(#151) - 0.24.0 - Supporting http-basic auth in WebSocketApp (#143) - fix failure of test.testInternalRecvStrict(#141) - skip utf8 validation by skip_utf8_validation argument (#137) - WebsocketProxyException will be raised if we got error about proxy.(#138) - 0.23.0 - Remove spurious print statement. (#135) - 0.22.0 - Fix not thread-safe of Websocket.close() (#120) - Try to get proxy info from environment if not explicitly provided (#124) - support proxy basic authentication. (#125) - Fix NoneType exception at WebsocketApp.send (#126) - not use proxy for localhost (#132) - 0.21.0 - Check for socket before attempting to close (#115) - Enable turning off SSL verification in wsdump.py(#116) - Enable to set subprotocol(#118) - Better support for Autobahn test suite (http://autobahn.ws/testsuite) (#117) - v0.20.0 - fix typo. - v0.19.0 - suppress close event message(#107) - detect socket connection state(#109) - support for code and reason in on_close callback(#111) - continuation frame handling seems suspicious(#113) - v0.18.0 - allow override of match_hostname usage on ssl (#105) - v0.17.0 - can't set timeout on a standing websocket connection (#102) - fixed local variable 'error' referenced before assignment (#102, #98) - v0.16.0 - lock some method for multithread. (#92) - disable cert verification. (#89) - v0.15.0 - fixed exception when send a large message (#84) - v0.14.1 - fixed to work on Python2.6 (#83) - v0.14.0 - Support python 3(#73) - Support IPv6(#77) - Support explicit web proxy(#57) - specify cookie in connect method option(#82) - v0.13.0 - MemoryError when receiving large amount of data (~60 MB) at once(ISSUE#59) - Controlling fragmentation(ISSUE#55) - server certificate validation(ISSUE#56) - PyPI tarball is missing test_websocket.py(ISSUE#65) - Payload length encoding bug(ISSUE#58) - disable Nagle algorithm by default(ISSUE#41) - Better event loop in WebSocketApp(ISSUE#63) - Skip tests that require Internet access by default(ISSUE#66) - v0.12.0 - support keep alive for WebSocketApp(ISSUE#34) - fix some SSL bugs(ISSUE#35, #36) - fix "Timing out leaves websocket library in bad state"(ISSUE#37) - fix "WebSocketApp.run_with_no_err() silently eats all exceptions"(ISSUE#38) - WebSocketTimeoutException will be raised for ws/wss timeout(ISSUE#40) - improve wsdump message(ISSUE#42) - support fragmentation message(ISSUE#43) - fix some bugs - v0.11.0 - Only log non-normal close status(ISSUE#31) - Fix default Origin isn't URI(ISSUE#32) - fileno support(ISSUE#33) - v0.10.0 - allow to set HTTP Header to WebSocketApp(ISSUE#27) - fix typo in pydoc(ISSUE#28) - Passing a socketopt flag to the websocket constructor(ISSUE#29) - websocket.send fails with long data(ISSUE#30) - v0.9.0 - allow to set opcode in WebSocketApp.send(ISSUE#25) - allow to modify Origin(ISSUE#26) - v0.8.0 - many bug fix - some performance improvement - v0.7.0 - fixed problem to read long data.(ISSUE#12) - fix buffer size boundary violation - v0.6.0 - Patches: UUID4, self.keep_running, mask_key (ISSUE#11) - add wsdump.py tool - v0.5.2 - fix Echo App Demo Throw Error: 'NoneType' object has no attribute 'opcode (ISSUE#10) - v0.5.1 - delete invalid print statement. - v0.5.0 - support hybi-13 protocol. - v0.4.1 - fix incorrect custom header order(ISSUE#1) websocket-client-1.7.0/LICENSE000066400000000000000000000261131453274240000157720ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. websocket-client-1.7.0/MANIFEST.in000066400000000000000000000001211453274240000165120ustar00rootroot00000000000000include LICENSE include README.md include ChangeLog recursive-include examples * websocket-client-1.7.0/README.md000066400000000000000000000141211453274240000162400ustar00rootroot00000000000000[![docs](https://readthedocs.org/projects/websocket-client/badge/?style=flat)](https://websocket-client.readthedocs.io/) [![Build Status](https://github.com/websocket-client/websocket-client/actions/workflows/build.yml/badge.svg)](https://github.com/websocket-client/websocket-client/actions/workflows/build.yml) [![codecov](https://codecov.io/gh/websocket-client/websocket-client/branch/master/graph/badge.svg?token=pcXhUQwiL3)](https://codecov.io/gh/websocket-client/websocket-client) [![PyPI Downloads](https://pepy.tech/badge/websocket-client)](https://pepy.tech/project/websocket-client) [![PyPI version](https://img.shields.io/pypi/v/websocket_client)](https://pypi.org/project/websocket_client/) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) # websocket-client websocket-client is a WebSocket client for Python. It provides access to low level APIs for WebSockets. websocket-client implements version [hybi-13](https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-13) of the WebSocket protocol. This client does not currently support the permessage-deflate extension from [RFC 7692](https://tools.ietf.org/html/rfc7692). ## Documentation This project's documentation can be found at [https://websocket-client.readthedocs.io/](https://websocket-client.readthedocs.io/) ## Contributing Please see the [contribution guidelines](https://github.com/websocket-client/websocket-client/blob/master/CONTRIBUTING.md) ## Installation You can use either `python3 setup.py install` or `pip3 install websocket-client` to 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 install `python-socks` for proxy usage and `wsaccel` for a minor performance boost, use: `pip3 install websocket-client[optional]` - To install `websockets` to run unit tests using the local echo server, use: `pip3 install websocket-client[test]` - To install `Sphinx` and `sphinx_rtd_theme` to build project documentation, use: `pip3 install websocket-client[docs]` While not a strict dependency, [rel](https://github.com/bubbleboy14/registeredeventlistener) is useful when using `run_forever` with automatic reconnect. Install rel with `pip3 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](https://websocket-client.readthedocs.io/en/latest/faq.html) Known issues with this library include lack of WebSocket Compression support (RFC 7692) and [minimal threading documentation/support](https://websocket-client.readthedocs.io/en/latest/threading.html). ## Performance The `send` and `validate_utf8` methods can sometimes be bottleneck. You can disable UTF8 validation in this library (and receive a performance enhancement) with the `skip_utf8_validation` parameter. 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 the `send` process. Numpy used to be a suggested performance enhancement alternative, but [issue #687](https://github.com/websocket-client/websocket-client/issues/687) found it didn't help. ## Examples Many more examples are found in the [examples documentation](https://websocket-client.readthedocs.io/en/latest/examples.html). ### Long-lived Connection Most real-world WebSockets situations involve longer-lived connections. The WebSocketApp `run_forever` loop will automatically try to reconnect to an open WebSocket connection when a network connection 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 controls using callbacks like `on_message` and `on_error`. `run_forever` **does not automatically reconnect** if the server closes the WebSocket gracefully (returning [a standard websocket close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1)). [This is the logic](https://github.com/websocket-client/websocket-client/pull/838#issuecomment-1228454826) behind the decision. Customizing behavior when the server closes the WebSocket should be handled in the `on_close` callback. This example uses [rel](https://github.com/bubbleboy14/registeredeventlistener) for the dispatcher to provide automatic reconnection. ```python import websocket import _thread import time import rel def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws, close_status_code, close_msg): print("### closed ###") def on_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 unexpectedly rel.signal(2, rel.abort) # Keyboard Interrupt rel.dispatch() ``` ### Short-lived Connection This 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. ```python from websocket import create_connection ws = 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() ``` websocket-client-1.7.0/compliance/000077500000000000000000000000001453274240000170745ustar00rootroot00000000000000websocket-client-1.7.0/compliance/README.md000066400000000000000000000015751453274240000203630ustar00rootroot00000000000000# Autobahn Testsuite General information and installation instructions are available at https://crossbar.io/autobahn/. ## Running the test suite 1. Install autobahn using `pip2 install autobahntestsuite`. Note that the [autobahn instructions](https://github.com/crossbario/autobahn-testsuite#installation) states that this is an outdated installation method only for Python 2, so this should be updated at some point. 2. (Optional) If you try step 1 and get an error from gcc stating "Python.h: No such file or directory", then install the python-dev package (specifically the one for Python 2) 3. Run `wstest -m fuzzingserver` 4. Make note of the port number that the server from step 3 is running on, then modify the `test_fuzzingclient.py` file accordingly 5. Run `python test_fuzzingclient.py` 6. When the test is complete, the results will be saved in a directory named `reports` websocket-client-1.7.0/compliance/autobahn-test-report-Feb-03-2021.html000066400000000000000000014540511453274240000253570ustar00rootroot00000000000000
Toggle Details

Autobahn WebSocket Testsuite Report
Autobahn WebSocket

Summary report generated on 2021-02-04T04:53:03.594Z (UTC) by Autobahn WebSocket Testsuite v0.8.1/v0.10.9.

Pass Test case was executed and passed successfully.
Non-Strict Test case was executed and passed non-strictly. A non-strict behavior is one that does not adhere to a SHOULD-behavior as described in the protocol specification or a well-defined, canonical behavior that appears to be desirable but left open in the protocol specification. An implementation with non-strict behavior is still conformant to the protocol specification.
Fail Test case was executed and failed. An implementation which fails a test case - other than a performance/limits related one - is non-conforming to a MUST-behavior as described in the protocol specification.
Info Informational test case which detects certain implementation behavior left unspecified by the spec but nevertheless potentially interesting to implementors.
Missing Test case is missing, either because it was skipped via the test suite configuration or deactivated, i.e. because the implementation does not implement the tested feature or breaks during running the test case.
1 Framing py-websockets-client
1.1 Text Messages
Case 1.1.1 Pass1000
Case 1.1.2 Pass1000
Case 1.1.3 Pass1000
Case 1.1.4 Pass1000
Case 1.1.5 Pass1000
Case 1.1.6 Pass1000
Case 1.1.7 Pass1000
Case 1.1.8 Pass1000
1 Framing py-websockets-client
1.2 Binary Messages
Case 1.2.1 Pass1000
Case 1.2.2 Pass1000
Case 1.2.3 Pass1000
Case 1.2.4 Pass1000
Case 1.2.5 Pass1000
Case 1.2.6 Pass1000
Case 1.2.7 Pass1000
Case 1.2.8 Pass1000
2 Pings/Pongs py-websockets-client
Case 2.1 Pass1000
Case 2.2 Pass1000
Case 2.3 Pass1000
Case 2.4 Pass1000
Case 2.5 Pass1002
Case 2.6 Pass1000
Case 2.7 Pass1000
Case 2.8 Pass1000
Case 2.9 Pass1000
Case 2.10 Pass1000
Case 2.11 Pass1000
3 Reserved Bits py-websockets-client
Case 3.1 Pass1002
Case 3.2 Pass1002
Case 3.3 Pass1002
Case 3.4 Pass1002
Case 3.5 Pass1002
Case 3.6 Pass1002
Case 3.7 Pass1002
4 Opcodes py-websockets-client
4.1 Non-control Opcodes
Case 4.1.1 Pass1002
Case 4.1.2 Pass1002
Case 4.1.3 Pass1002
Case 4.1.4 Pass1002
Case 4.1.5 Pass1002
4 Opcodes py-websockets-client
4.2 Control Opcodes
Case 4.2.1 Pass1002
Case 4.2.2 Pass1002
Case 4.2.3 Pass1002
Case 4.2.4 Pass1002
Case 4.2.5 Pass1002
5 Fragmentation py-websockets-client
Case 5.1 Pass1002
Case 5.2 Pass1002
Case 5.3 Pass1000
Case 5.4 Pass1000
Case 5.5 Pass1000
Case 5.6 Pass1000
Case 5.7 Pass1000
Case 5.8 Pass1000
Case 5.9 Pass1002
Case 5.10 Pass1002
Case 5.11 Pass1002
Case 5.12 Pass1002
Case 5.13 Pass1002
Case 5.14 Pass1002
Case 5.15 Pass1002
Case 5.16 Pass1002
Case 5.17 Pass1002
Case 5.18 Pass1002
Case 5.19 Pass1000
Case 5.20 Pass1000
6 UTF-8 Handling py-websockets-client
6.1 Valid UTF-8 with zero payload fragments
Case 6.1.1 Pass1000
Case 6.1.2 Pass1000
Case 6.1.3 Pass1000
6 UTF-8 Handling py-websockets-client
6.2 Valid UTF-8 unfragmented, fragmented on code-points and within code-points
Case 6.2.1 Pass1000
Case 6.2.2 Pass1000
Case 6.2.3 Pass1000
Case 6.2.4 Pass1000
6 UTF-8 Handling py-websockets-client
6.3 Invalid UTF-8 differently fragmented
Case 6.3.1 Pass1007
Case 6.3.2 Pass1007
6 UTF-8 Handling py-websockets-client
6.4 Fail-fast on invalid UTF-8
Case 6.4.1 Non-Strict1007
Case 6.4.2 Non-Strict1007
Case 6.4.3 Non-Strict1007
Case 6.4.4 Non-Strict1007
6 UTF-8 Handling py-websockets-client
6.5 Some valid UTF-8 sequences
Case 6.5.1 Pass1000
Case 6.5.2 Pass1000
Case 6.5.3 Pass1000
Case 6.5.4 Pass1000
Case 6.5.5 Pass1000
6 UTF-8 Handling py-websockets-client
6.6 All prefixes of a valid UTF-8 string that contains multi-byte code points
Case 6.6.1 Pass1002
Case 6.6.2 Pass1000
Case 6.6.3 Pass1002
Case 6.6.4 Pass1002
Case 6.6.5 Pass1000
Case 6.6.6 Pass1002
Case 6.6.7 Pass1000
Case 6.6.8 Pass1002
Case 6.6.9 Pass1000
Case 6.6.10 Pass1002
Case 6.6.11 Pass1000
6 UTF-8 Handling py-websockets-client
6.7 First possible sequence of a certain length
Case 6.7.1 Pass1000
Case 6.7.2 Pass1000
Case 6.7.3 Pass1000
Case 6.7.4 Pass1000
6 UTF-8 Handling py-websockets-client
6.8 First possible sequence length 5/6 (invalid codepoints)
Case 6.8.1 Pass1007
Case 6.8.2 Pass1007
6 UTF-8 Handling py-websockets-client
6.9 Last possible sequence of a certain length
Case 6.9.1 Pass1000
Case 6.9.2 Pass1000
Case 6.9.3 Pass1000
Case 6.9.4 Pass1000
6 UTF-8 Handling py-websockets-client
6.10 Last possible sequence length 4/5/6 (invalid codepoints)
Case 6.10.1 Pass1007
Case 6.10.2 Pass1007
Case 6.10.3 Pass1007
6 UTF-8 Handling py-websockets-client
6.11 Other boundary conditions
Case 6.11.1 Pass1000
Case 6.11.2 Pass1000
Case 6.11.3 Pass1000
Case 6.11.4 Pass1000
Case 6.11.5 Pass1007
6 UTF-8 Handling py-websockets-client
6.12 Unexpected continuation bytes
Case 6.12.1 Pass1007
Case 6.12.2 Pass1007
Case 6.12.3 Pass1007
Case 6.12.4 Pass1007
Case 6.12.5 Pass1007
Case 6.12.6 Pass1007
Case 6.12.7 Pass1007
Case 6.12.8 Pass1007
6 UTF-8 Handling py-websockets-client
6.13 Lonely start characters
Case 6.13.1 Pass1007
Case 6.13.2 Pass1007
Case 6.13.3 Pass1007
Case 6.13.4 Pass1007
Case 6.13.5 Pass1007
6 UTF-8 Handling py-websockets-client
6.14 Sequences with last continuation byte missing
Case 6.14.1 Pass1007
Case 6.14.2 Pass1007
Case 6.14.3 Pass1007
Case 6.14.4 Pass1007
Case 6.14.5 Pass1007
Case 6.14.6 Pass1002
Case 6.14.7 Pass1002
Case 6.14.8 Pass1007
Case 6.14.9 Pass1007
Case 6.14.10 Pass1007
6 UTF-8 Handling py-websockets-client
6.15 Concatenation of incomplete sequences
Case 6.15.1 Pass1007
6 UTF-8 Handling py-websockets-client
6.16 Impossible bytes
Case 6.16.1 Pass1007
Case 6.16.2 Pass1007
Case 6.16.3 Pass1007
6 UTF-8 Handling py-websockets-client
6.17 Examples of an overlong ASCII character
Case 6.17.1 Pass1007
Case 6.17.2 Pass1007
Case 6.17.3 Pass1007
Case 6.17.4 Pass1007
Case 6.17.5 Pass1007
6 UTF-8 Handling py-websockets-client
6.18 Maximum overlong sequences
Case 6.18.1 Pass1007
Case 6.18.2 Pass1007
Case 6.18.3 Pass1007
Case 6.18.4 Pass1007
Case 6.18.5 Pass1007
6 UTF-8 Handling py-websockets-client
6.19 Overlong representation of the NUL character
Case 6.19.1 Pass1007
Case 6.19.2 Pass1007
Case 6.19.3 Pass1007
Case 6.19.4 Pass1007
Case 6.19.5 Pass1007
6 UTF-8 Handling py-websockets-client
6.20 Single UTF-16 surrogates
Case 6.20.1 Pass1007
Case 6.20.2 Pass1007
Case 6.20.3 Pass1007
Case 6.20.4 Pass1007
Case 6.20.5 Pass1007
Case 6.20.6 Pass1007
Case 6.20.7 Pass1007
6 UTF-8 Handling py-websockets-client
6.21 Paired UTF-16 surrogates
Case 6.21.1 Pass1007
Case 6.21.2 Pass1007
Case 6.21.3 Pass1007
Case 6.21.4 Pass1007
Case 6.21.5 Pass1007
Case 6.21.6 Pass1007
Case 6.21.7 Pass1007
Case 6.21.8 Pass1007
6 UTF-8 Handling py-websockets-client
6.22 Non-character code points (valid UTF-8)
Case 6.22.1 Pass1000
Case 6.22.2 Pass1000
Case 6.22.3 Pass1000
Case 6.22.4 Pass1000
Case 6.22.5 Pass1000
Case 6.22.6 Pass1000
Case 6.22.7 Pass1000
Case 6.22.8 Pass1000
Case 6.22.9 Pass1000
Case 6.22.10 Pass1000
Case 6.22.11 Pass1000
Case 6.22.12 Pass1000
Case 6.22.13 Pass1000
Case 6.22.14 Pass1000
Case 6.22.15 Pass1000
Case 6.22.16 Pass1000
Case 6.22.17 Pass1000
Case 6.22.18 Pass1000
Case 6.22.19 Pass1000
Case 6.22.20 Pass1000
Case 6.22.21 Pass1000
Case 6.22.22 Pass1000
Case 6.22.23 Pass1000
Case 6.22.24 Pass1000
Case 6.22.25 Pass1000
Case 6.22.26 Pass1000
Case 6.22.27 Pass1000
Case 6.22.28 Pass1000
Case 6.22.29 Pass1000
Case 6.22.30 Pass1000
Case 6.22.31 Pass1000
Case 6.22.32 Pass1000
Case 6.22.33 Pass1000
Case 6.22.34 Pass1000
6 UTF-8 Handling py-websockets-client
6.23 Unicode specials (i.e. replacement char)
Case 6.23.1 Pass1000
Case 6.23.2 Pass1000
Case 6.23.3 Pass1000
Case 6.23.4 Pass1000
Case 6.23.5 Pass1000
Case 6.23.6 Pass1000
Case 6.23.7 Pass1000
7 Close Handling py-websockets-client
7.1 Basic close behavior (fuzzer initiated)
Case 7.1.1 Pass1000
Case 7.1.2 Pass1000
Case 7.1.3 Pass1000
Case 7.1.4 Pass1000
Case 7.1.5 Pass1000
Case 7.1.6 Info1000
7 Close Handling py-websockets-client
7.3 Close frame structure: payload length (fuzzer initiated)
Case 7.3.1 Pass1000
Case 7.3.2 Pass1002
Case 7.3.3 Pass1000
Case 7.3.4 Pass1000
Case 7.3.5 Pass1000
Case 7.3.6 Pass1002
7 Close Handling py-websockets-client
7.5 Close frame structure: payload value (fuzzer initiated)
Case 7.5.1 Pass1002
7 Close Handling py-websockets-client
7.7 Close frame structure: valid close codes (fuzzer initiated)
Case 7.7.1 Pass1000
Case 7.7.2 Pass1000
Case 7.7.3 Pass1000
Case 7.7.4 Pass1000
Case 7.7.5 Pass1000
Case 7.7.6 Pass1000
Case 7.7.7 Pass1000
Case 7.7.8 Pass1000
Case 7.7.9 Pass1000
Case 7.7.10 Pass1000
Case 7.7.11 Pass1000
Case 7.7.12 Pass1000
Case 7.7.13 Pass1000
7 Close Handling py-websockets-client
7.9 Close frame structure: invalid close codes (fuzzer initiated)
Case 7.9.1 Pass1002
Case 7.9.2 Pass1002
Case 7.9.3 Pass1002
Case 7.9.4 Pass1002
Case 7.9.5 Pass1002
Case 7.9.6 Pass1002
Case 7.9.7 Pass1002
Case 7.9.8 Pass1002
Case 7.9.9 Pass1002
7 Close Handling py-websockets-client
7.13 Informational close information (fuzzer initiated)
Case 7.13.1 Info1002
Case 7.13.2 Info1002
9 Limits/Performance py-websockets-client
9.1 Text Message (increasing size)
Case 9.1.1 Pass
52 ms
1000
Case 9.1.2 Pass
186 ms
1000
Case 9.1.3 Pass
703 ms
1000
Case 9.1.4 Pass
2824 ms
1000
Case 9.1.5 Pass
5517 ms
1000
Case 9.1.6 Pass
11123 ms
1000
9 Limits/Performance py-websockets-client
9.2 Binary Message (increasing size)
Case 9.2.1 Pass
12 ms
1000
Case 9.2.2 Pass
45 ms
1000
Case 9.2.3 Pass
173 ms
1000
Case 9.2.4 Pass
699 ms
1000
Case 9.2.5 Pass
1393 ms
1000
Case 9.2.6 Pass
2790 ms
1000
9 Limits/Performance py-websockets-client
9.3 Fragmented Text Message (fixed size, increasing fragment size)
Case 9.3.1 Pass
15470 ms
1000
Case 9.3.2 Pass
5939 ms
1000
Case 9.3.3 Pass
3600 ms
1000
Case 9.3.4 Pass
3096 ms
1000
Case 9.3.5 Pass
3005 ms
1000
Case 9.3.6 Pass
2755 ms
1000
Case 9.3.7 Pass
2864 ms
1000
Case 9.3.8 Pass
2743 ms
1000
Case 9.3.9 Pass
2731 ms
1000
9 Limits/Performance py-websockets-client
9.4 Fragmented Binary Message (fixed size, increasing fragment size)
Case 9.4.1 Pass
13318 ms
1000
Case 9.4.2 Pass
3838 ms
1000
Case 9.4.3 Pass
1449 ms
1000
Case 9.4.4 Pass
854 ms
1000
Case 9.4.5 Pass
701 ms
1000
Case 9.4.6 Pass
660 ms
1000
Case 9.4.7 Pass
642 ms
1000
Case 9.4.8 Pass
649 ms
1000
Case 9.4.9 Pass
638 ms
1000
9 Limits/Performance py-websockets-client
9.5 Text Message (fixed size, increasing chop size)
Case 9.5.1 Pass
1269 ms
1000
Case 9.5.2 Pass
967 ms
1000
Case 9.5.3 Pass
831 ms
1000
Case 9.5.4 Pass
756 ms
1000
Case 9.5.5 Pass
728 ms
1000
Case 9.5.6 Pass
734 ms
1000
9 Limits/Performance py-websockets-client
9.6 Binary Text Message (fixed size, increasing chop size)
Case 9.6.1 Pass
741 ms
1000
Case 9.6.2 Pass
464 ms
1000
Case 9.6.3 Pass
315 ms
1000
Case 9.6.4 Pass
245 ms
1000
Case 9.6.5 Pass
218 ms
1000
Case 9.6.6 Pass
197 ms
1000
9 Limits/Performance py-websockets-client
9.7 Text Message Roundtrip Time (fixed number, increasing size)
Case 9.7.1 Pass
140 ms
1000
Case 9.7.2 Pass
137 ms
1000
Case 9.7.3 Pass
185 ms
1000
Case 9.7.4 Pass
447 ms
1000
Case 9.7.5 Pass
1030 ms
1000
Case 9.7.6 Pass
3221 ms
1000
9 Limits/Performance py-websockets-client
9.8 Binary Message Roundtrip Time (fixed number, increasing size)
Case 9.8.1 Pass
97 ms
1000
Case 9.8.2 Pass
108 ms
1000
Case 9.8.3 Pass
117 ms
1000
Case 9.8.4 Pass
166 ms
1000
Case 9.8.5 Pass
411 ms
1000
Case 9.8.6 Pass
983 ms
1000
10 Misc py-websockets-client
10.1 Auto-Fragmentation
Case 10.1.1 Pass1000
12 WebSocket Compression (different payloads) py-websockets-client
12.1 Large JSON data file (utf8, 194056 bytes)
Case 12.1.1 Unimplemented
Case 12.1.2 Unimplemented
Case 12.1.3 Unimplemented
Case 12.1.4 Unimplemented
Case 12.1.5 Unimplemented
Case 12.1.6 Unimplemented
Case 12.1.7 Unimplemented
Case 12.1.8 Unimplemented
Case 12.1.9 Unimplemented
Case 12.1.10 Unimplemented
Case 12.1.11 Unimplemented
Case 12.1.12 Unimplemented
Case 12.1.13 Unimplemented
Case 12.1.14 Unimplemented
Case 12.1.15 Unimplemented
Case 12.1.16 Unimplemented
Case 12.1.17 Unimplemented
Case 12.1.18 Unimplemented
12 WebSocket Compression (different payloads) py-websockets-client
12.2 Lena Picture, Bitmap 512x512 bw (binary, 263222 bytes)
Case 12.2.1 Unimplemented
Case 12.2.2 Unimplemented
Case 12.2.3 Unimplemented
Case 12.2.4 Unimplemented
Case 12.2.5 Unimplemented
Case 12.2.6 Unimplemented
Case 12.2.7 Unimplemented
Case 12.2.8 Unimplemented
Case 12.2.9 Unimplemented
Case 12.2.10 Unimplemented
Case 12.2.11 Unimplemented
Case 12.2.12 Unimplemented
Case 12.2.13 Unimplemented
Case 12.2.14 Unimplemented
Case 12.2.15 Unimplemented
Case 12.2.16 Unimplemented
Case 12.2.17 Unimplemented
Case 12.2.18 Unimplemented
12 WebSocket Compression (different payloads) py-websockets-client
12.3 Human readable text, Goethe's Faust I (German) (binary, 222218 bytes)
Case 12.3.1 Unimplemented
Case 12.3.2 Unimplemented
Case 12.3.3 Unimplemented
Case 12.3.4 Unimplemented
Case 12.3.5 Unimplemented
Case 12.3.6 Unimplemented
Case 12.3.7 Unimplemented
Case 12.3.8 Unimplemented
Case 12.3.9 Unimplemented
Case 12.3.10 Unimplemented
Case 12.3.11 Unimplemented
Case 12.3.12 Unimplemented
Case 12.3.13 Unimplemented
Case 12.3.14 Unimplemented
Case 12.3.15 Unimplemented
Case 12.3.16 Unimplemented
Case 12.3.17 Unimplemented
Case 12.3.18 Unimplemented
12 WebSocket Compression (different payloads) py-websockets-client
12.4 Large HTML file (utf8, 263527 bytes)
Case 12.4.1 Unimplemented
Case 12.4.2 Unimplemented
Case 12.4.3 Unimplemented
Case 12.4.4 Unimplemented
Case 12.4.5 Unimplemented
Case 12.4.6 Unimplemented
Case 12.4.7 Unimplemented
Case 12.4.8 Unimplemented
Case 12.4.9 Unimplemented
Case 12.4.10 Unimplemented
Case 12.4.11 Unimplemented
Case 12.4.12 Unimplemented
Case 12.4.13 Unimplemented
Case 12.4.14 Unimplemented
Case 12.4.15 Unimplemented
Case 12.4.16 Unimplemented
Case 12.4.17 Unimplemented
Case 12.4.18 Unimplemented
12 WebSocket Compression (different payloads) py-websockets-client
12.5 A larger PDF (binary, 1042328 bytes)
Case 12.5.1 Unimplemented
Case 12.5.2 Unimplemented
Case 12.5.3 Unimplemented
Case 12.5.4 Unimplemented
Case 12.5.5 Unimplemented
Case 12.5.6 Unimplemented
Case 12.5.7 Unimplemented
Case 12.5.8 Unimplemented
Case 12.5.9 Unimplemented
Case 12.5.10 Unimplemented
Case 12.5.11 Unimplemented
Case 12.5.12 Unimplemented
Case 12.5.13 Unimplemented
Case 12.5.14 Unimplemented
Case 12.5.15 Unimplemented
Case 12.5.16 Unimplemented
Case 12.5.17 Unimplemented
Case 12.5.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.1 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]
Case 13.1.1 Unimplemented
Case 13.1.2 Unimplemented
Case 13.1.3 Unimplemented
Case 13.1.4 Unimplemented
Case 13.1.5 Unimplemented
Case 13.1.6 Unimplemented
Case 13.1.7 Unimplemented
Case 13.1.8 Unimplemented
Case 13.1.9 Unimplemented
Case 13.1.10 Unimplemented
Case 13.1.11 Unimplemented
Case 13.1.12 Unimplemented
Case 13.1.13 Unimplemented
Case 13.1.14 Unimplemented
Case 13.1.15 Unimplemented
Case 13.1.16 Unimplemented
Case 13.1.17 Unimplemented
Case 13.1.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.2 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]
Case 13.2.1 Unimplemented
Case 13.2.2 Unimplemented
Case 13.2.3 Unimplemented
Case 13.2.4 Unimplemented
Case 13.2.5 Unimplemented
Case 13.2.6 Unimplemented
Case 13.2.7 Unimplemented
Case 13.2.8 Unimplemented
Case 13.2.9 Unimplemented
Case 13.2.10 Unimplemented
Case 13.2.11 Unimplemented
Case 13.2.12 Unimplemented
Case 13.2.13 Unimplemented
Case 13.2.14 Unimplemented
Case 13.2.15 Unimplemented
Case 13.2.16 Unimplemented
Case 13.2.17 Unimplemented
Case 13.2.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.3 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]
Case 13.3.1 Unimplemented
Case 13.3.2 Unimplemented
Case 13.3.3 Unimplemented
Case 13.3.4 Unimplemented
Case 13.3.5 Unimplemented
Case 13.3.6 Unimplemented
Case 13.3.7 Unimplemented
Case 13.3.8 Unimplemented
Case 13.3.9 Unimplemented
Case 13.3.10 Unimplemented
Case 13.3.11 Unimplemented
Case 13.3.12 Unimplemented
Case 13.3.13 Unimplemented
Case 13.3.14 Unimplemented
Case 13.3.15 Unimplemented
Case 13.3.16 Unimplemented
Case 13.3.17 Unimplemented
Case 13.3.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.4 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]
Case 13.4.1 Unimplemented
Case 13.4.2 Unimplemented
Case 13.4.3 Unimplemented
Case 13.4.4 Unimplemented
Case 13.4.5 Unimplemented
Case 13.4.6 Unimplemented
Case 13.4.7 Unimplemented
Case 13.4.8 Unimplemented
Case 13.4.9 Unimplemented
Case 13.4.10 Unimplemented
Case 13.4.11 Unimplemented
Case 13.4.12 Unimplemented
Case 13.4.13 Unimplemented
Case 13.4.14 Unimplemented
Case 13.4.15 Unimplemented
Case 13.4.16 Unimplemented
Case 13.4.17 Unimplemented
Case 13.4.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.5 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]
Case 13.5.1 Unimplemented
Case 13.5.2 Unimplemented
Case 13.5.3 Unimplemented
Case 13.5.4 Unimplemented
Case 13.5.5 Unimplemented
Case 13.5.6 Unimplemented
Case 13.5.7 Unimplemented
Case 13.5.8 Unimplemented
Case 13.5.9 Unimplemented
Case 13.5.10 Unimplemented
Case 13.5.11 Unimplemented
Case 13.5.12 Unimplemented
Case 13.5.13 Unimplemented
Case 13.5.14 Unimplemented
Case 13.5.15 Unimplemented
Case 13.5.16 Unimplemented
Case 13.5.17 Unimplemented
Case 13.5.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.6 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]
Case 13.6.1 Unimplemented
Case 13.6.2 Unimplemented
Case 13.6.3 Unimplemented
Case 13.6.4 Unimplemented
Case 13.6.5 Unimplemented
Case 13.6.6 Unimplemented
Case 13.6.7 Unimplemented
Case 13.6.8 Unimplemented
Case 13.6.9 Unimplemented
Case 13.6.10 Unimplemented
Case 13.6.11 Unimplemented
Case 13.6.12 Unimplemented
Case 13.6.13 Unimplemented
Case 13.6.14 Unimplemented
Case 13.6.15 Unimplemented
Case 13.6.16 Unimplemented
Case 13.6.17 Unimplemented
Case 13.6.18 Unimplemented
13 WebSocket Compression (different parameters) py-websockets-client
13.7 Large JSON data file (utf8, 194056 bytes) - client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)] / server accept (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]
Case 13.7.1 Unimplemented
Case 13.7.2 Unimplemented
Case 13.7.3 Unimplemented
Case 13.7.4 Unimplemented
Case 13.7.5 Unimplemented
Case 13.7.6 Unimplemented
Case 13.7.7 Unimplemented
Case 13.7.8 Unimplemented
Case 13.7.9 Unimplemented
Case 13.7.10 Unimplemented
Case 13.7.11 Unimplemented
Case 13.7.12 Unimplemented
Case 13.7.13 Unimplemented
Case 13.7.14 Unimplemented
Case 13.7.15 Unimplemented
Case 13.7.16 Unimplemented
Case 13.7.17 Unimplemented
Case 13.7.18 Unimplemented



Case 1.1.1

Up

Case Description

Send text message with payload 0.

Case Expectation

Receive echo'ed text message (with empty payload). Clean close with normal code.


Case 1.1.2

Up

Case Description

Send text message message with payload of length 125.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.1.3

Up

Case Description

Send text message message with payload of length 126.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.1.4

Up

Case Description

Send text message message with payload of length 127.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.1.5

Up

Case Description

Send text message message with payload of length 128.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.1.6

Up

Case Description

Send text message message with payload of length 65535.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.1.7

Up

Case Description

Send text message message with payload of length 65536.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.1.8

Up

Case Description

Send text message message with payload of length 65536. Sent out data in chops of 997 octets.

Case Expectation

Receive echo'ed text message (with payload as sent). Clean close with normal code.


Case 1.2.1

Up

Case Description

Send binary message with payload 0.

Case Expectation

Receive echo'ed binary message (with empty payload). Clean close with normal code.


Case 1.2.2

Up

Case Description

Send binary message message with payload of length 125.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 1.2.3

Up

Case Description

Send binary message message with payload of length 126.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 1.2.4

Up

Case Description

Send binary message message with payload of length 127.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 1.2.5

Up

Case Description

Send binary message message with payload of length 128.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 1.2.6

Up

Case Description

Send binary message message with payload of length 65535.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 1.2.7

Up

Case Description

Send binary message message with payload of length 65536.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 1.2.8

Up

Case Description

Send binary message message with payload of length 65536. Sent out data in chops of 997 octets.

Case Expectation

Receive echo'ed binary message (with payload as sent). Clean close with normal code.


Case 2.1

Up

Case Description

Send ping without payload.

Case Expectation

Pong (with empty payload) is sent in reply to Ping. Clean close with normal code.


Case 2.2

Up

Case Description

Send ping with small text payload.

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.


Case 2.3

Up

Case Description

Send ping with small binary (non UTF-8) payload.

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.


Case 2.4

Up

Case Description

Send ping with binary payload of 125 octets.

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Clean close with normal code.


Case 2.5

Up

Case Description

Send ping with binary payload of 126 octets.

Case Expectation

Connection is failed immediately (1002/Protocol Error), since control frames are only allowed to have payload up to and including 125 octets..


Case 2.6

Up

Case Description

Send ping with binary payload of 125 octets, send in octet-wise chops.

Case Expectation

Pong with payload echo'ed is sent in reply to Ping. Implementations must be TCP clean. Clean close with normal code.


Case 2.7

Up

Case Description

Send unsolicited pong without payload. Verify nothing is received. Clean close with normal code.

Case Expectation

Nothing.


Case 2.8

Up

Case Description

Send unsolicited pong with payload. Verify nothing is received. Clean close with normal code.

Case Expectation

Nothing.


Case 2.9

Up

Case Description

Send unsolicited pong with payload. Send ping with payload. Verify pong for ping is received.

Case Expectation

Nothing in reply to own Pong, but Pong with payload echo'ed in reply to Ping. Clean close with normal code.


Case 2.10

Up

Case Description

Send 10 Pings with payload.

Case Expectation

Pongs for our Pings with all the payloads. Note: This is not required by the Spec .. but we check for this behaviour anyway. Clean close with normal code.


Case 2.11

Up

Case Description

Send 10 Pings with payload. Send out octets in octet-wise chops.

Case Expectation

Pongs for our Pings with all the payloads. Note: This is not required by the Spec .. but we check for this behaviour anyway. Clean close with normal code.


Case 3.1

Up

Case Description

Send small text message with RSV = 1.

Case Expectation

The connection is failed immediately (1002/protocol error), since RSV must be 0, when no extension defining RSV meaning has been negotiated.


Case 3.2

Up

Case Description

Send small text message, then send again with RSV = 2, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.


Case 3.3

Up

Case Description

Send small text message, then send again with RSV = 3, then send Ping. Octets are sent in frame-wise chops. Octets are sent in octet-wise chops.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.


Case 3.4

Up

Case Description

Send small text message, then send again with RSV = 4, then send Ping. Octets are sent in octet-wise chops.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since RSV must be 0, when no extension defining RSV meaning has been negotiated. The Pong is not received.


Case 3.5

Up

Case Description

Send small binary message with RSV = 5.

Case Expectation

The connection is failed immediately, since RSV must be 0.


Case 3.6

Up

Case Description

Send Ping with RSV = 6.

Case Expectation

The connection is failed immediately, since RSV must be 0.


Case 3.7

Up

Case Description

Send Close with RSV = 7.

Case Expectation

The connection is failed immediately, since RSV must be 0.


Case 4.1.1

Up

Case Description

Send frame with reserved non-control Opcode = 3.

Case Expectation

The connection is failed immediately.


Case 4.1.2

Up

Case Description

Send frame with reserved non-control Opcode = 4 and non-empty payload.

Case Expectation

The connection is failed immediately.


Case 4.1.3

Up

Case Description

Send small text message, then send frame with reserved non-control Opcode = 5, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.


Case 4.1.4

Up

Case Description

Send small text message, then send frame with reserved non-control Opcode = 6 and non-empty payload, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.


Case 4.1.5

Up

Case Description

Send small text message, then send frame with reserved non-control Opcode = 7 and non-empty payload, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.


Case 4.2.1

Up

Case Description

Send frame with reserved control Opcode = 11.

Case Expectation

The connection is failed immediately.


Case 4.2.2

Up

Case Description

Send frame with reserved control Opcode = 12 and non-empty payload.

Case Expectation

The connection is failed immediately.


Case 4.2.3

Up

Case Description

Send small text message, then send frame with reserved control Opcode = 13, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.


Case 4.2.4

Up

Case Description

Send small text message, then send frame with reserved control Opcode = 14 and non-empty payload, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.


Case 4.2.5

Up

Case Description

Send small text message, then send frame with reserved control Opcode = 15 and non-empty payload, then send Ping.

Case Expectation

Echo for first message is received, but then connection is failed immediately, since reserved opcode frame is used. A Pong is not received.


Case 5.1

Up

Case Description

Send Ping fragmented into 2 fragments.

Case Expectation

Connection is failed immediately, since control message MUST NOT be fragmented.


Case 5.2

Up

Case Description

Send Pong fragmented into 2 fragments.

Case Expectation

Connection is failed immediately, since control message MUST NOT be fragmented.


Case 5.3

Up

Case Description

Send text Message fragmented into 2 fragments.

Case Expectation

Message is processed and echo'ed back to us.


Case 5.4

Up

Case Description

Send text Message fragmented into 2 fragments, octets are sent in frame-wise chops.

Case Expectation

Message is processed and echo'ed back to us.


Case 5.5

Up

Case Description

Send text Message fragmented into 2 fragments, octets are sent in octet-wise chops.

Case Expectation

Message is processed and echo'ed back to us.


Case 5.6

Up

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between.

Case Expectation

A pong is received, then the message is echo'ed back to us.


Case 5.7

Up

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between. Octets are sent in frame-wise chops.

Case Expectation

A pong is received, then the message is echo'ed back to us.


Case 5.8

Up

Case Description

Send text Message fragmented into 2 fragments, one ping with payload in-between. Octets are sent in octet-wise chops.

Case Expectation

A pong is received, then the message is echo'ed back to us.


Case 5.9

Up

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in one chop.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.10

Up

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in per-frame chops.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.11

Up

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = true, where there is nothing to continue, sent in octet-wise chops.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.12

Up

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in one chop.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.13

Up

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in per-frame chops.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.14

Up

Case Description

Send unfragmented Text Message after Continuation Frame with FIN = false, where there is nothing to continue, sent in octet-wise chops.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.15

Up

Case Description

Send text Message fragmented into 2 fragments, then Continuation Frame with FIN = false where there is nothing to continue, then unfragmented Text Message, all sent in one chop.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.16

Up

Case Description

Repeated 2x: Continuation Frame with FIN = false (where there is nothing to continue), then text Message fragmented into 2 fragments.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.17

Up

Case Description

Repeated 2x: Continuation Frame with FIN = true (where there is nothing to continue), then text Message fragmented into 2 fragments.

Case Expectation

The connection is failed immediately, since there is no message to continue.


Case 5.18

Up

Case Description

Send text Message fragmented into 2 fragments, with both frame opcodes set to text, sent in one chop.

Case Expectation

The connection is failed immediately, since all data frames after the initial data frame must have opcode 0.


Case 5.19

Up

Case Description

A fragmented text message is sent in multiple frames. After sending the first 2 frames of the text message, a Ping is sent. Then we wait 1s, then we send 2 more text fragments, another Ping and then the final text fragment. Everything is legal.

Case Expectation

The peer immediately answers the first Ping before it has received the last text message fragment. The peer pong's back the Ping's payload exactly, and echo's the payload of the fragmented message back to us.


Case 5.20

Up

Case Description

Same as Case 5.19, but send all frames with SYNC = True. Note, this does not change the octets sent in any way, only how the stream is chopped up on the wire.

Case Expectation

Same as Case 5.19. Implementations must be agnostic to how octet stream is chopped up on wire (must be TCP clean).


Case 6.1.1

Up

Case Description

Send text message of length 0.

Case Expectation

A message is echo'ed back to us (with empty payload).


Case 6.1.2

Up

Case Description

Send fragmented text message, 3 fragments each of length 0.

Case Expectation

A message is echo'ed back to us (with empty payload).


Case 6.1.3

Up

Case Description

Send fragmented text message, 3 fragments, first and last of length 0, middle non-empty.

Case Expectation

A message is echo'ed back to us (with payload = payload of middle fragment).


Case 6.2.1

Up

Case Description

Send a valid UTF-8 text message in one fragment.

MESSAGE:
Hello-µ@ßöäüàá-UTF-8!!
48656c6c6f2dc2b540c39fc3b6c3a4c3bcc3a0c3a12d5554462d382121

Case Expectation

The message is echo'ed back to us.


Case 6.2.2

Up

Case Description

Send a valid UTF-8 text message in two fragments, fragmented on UTF-8 code point boundary.

MESSAGE FRAGMENT 1:
Hello-µ@ßöä
48656c6c6f2dc2b540c39fc3b6c3a4

MESSAGE FRAGMENT 2:
üàá-UTF-8!!
c3bcc3a0c3a12d5554462d382121

Case Expectation

The message is echo'ed back to us.


Case 6.2.3

Up

Case Description

Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
Hello-µ@ßöäüàá-UTF-8!!
48656c6c6f2dc2b540c39fc3b6c3a4c3bcc3a0c3a12d5554462d382121

Case Expectation

The message is echo'ed back to us.


Case 6.2.4

Up

Case Description

Send a valid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
κόσμε
cebae1bdb9cf83cebcceb5

Case Expectation

The message is echo'ed back to us.


Case 6.3.1

Up

Case Description

Send invalid UTF-8 text message unfragmented.

MESSAGE:
cebae1bdb9cf83cebcceb5eda080656469746564

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.3.2

Up

Case Description

Send invalid UTF-8 text message in fragments of 1 octet, resulting in frames ending on positions which are not code point ends.

MESSAGE:
cebae1bdb9cf83cebcceb5eda080656469746564

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.4.1

Up

Case Description

Send invalid UTF-8 text message in 3 fragments (frames). First frame payload is valid, then wait, then 2nd frame which contains the payload making the sequence invalid, then wait, then 3rd frame with rest. Note that PART1 and PART3 are valid UTF-8 in themselves, PART2 is a 0x110000 encoded as in the UTF-8 integer encoding scheme, but the codepoint is invalid (out of range).

MESSAGE PARTS:
PART1 = cebae1bdb9cf83cebcceb5
PART2 = f4908080
PART3 = 656469746564

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.


Case 6.4.2

Up

Case Description

Same as Case 6.4.1, but in 2nd frame, we send only up to and including the octet making the complete payload invalid.

MESSAGE PARTS:
PART1 = cebae1bdb9cf83cebcceb5f4
PART2 = 90
PART3 = 8080656469746564

Case Expectation

The first frame is accepted, we expect to timeout on the first wait. The 2nd frame should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.


Case 6.4.3

Up

Case Description

Same as Case 6.4.1, but we send message not in 3 frames, but in 3 chops of the same message frame.

MESSAGE PARTS:
PART1 = cebae1bdb9cf83cebcceb5
PART2 = f4908080
PART3 = 656469746564

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.


Case 6.4.4

Up

Case Description

Same as Case 6.4.2, but we send message not in 3 frames, but in 3 chops of the same message frame.

MESSAGE PARTS:
PART1 = cebae1bdb9cf83cebcceb5f4
PART2 = 90
PART3 =

Case Expectation

The first chop is accepted, we expect to timeout on the first wait. The 2nd chop should be rejected immediately (fail fast on UTF-8). If we timeout, we expect the connection is failed at least then, since the complete message payload is not valid UTF-8.


Case 6.5.1

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6f24776f726c64

Case Expectation

The message is echo'ed back to us.


Case 6.5.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6fc2a2776f726c64

Case Expectation

The message is echo'ed back to us.


Case 6.5.3

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6fe282ac776f726c64

Case Expectation

The message is echo'ed back to us.


Case 6.5.4

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x68656c6c6ff0a4ada2776f726c64

Case Expectation

The message is echo'ed back to us.


Case 6.5.5

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcceb5

Case Expectation

The message is echo'ed back to us.


Case 6.6.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xce

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xceba

Case Expectation

The message is echo'ed back to us.


Case 6.6.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bd

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.5

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9

Case Expectation

The message is echo'ed back to us.


Case 6.6.6

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.7

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83

Case Expectation

The message is echo'ed back to us.


Case 6.6.8

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83ce

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.9

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebc

Case Expectation

The message is echo'ed back to us.


Case 6.6.10

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcce

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.6.11

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xcebae1bdb9cf83cebcceb5

Case Expectation

The message is echo'ed back to us.


Case 6.7.1

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x00

Case Expectation

The message is echo'ed back to us.


Case 6.7.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xc280

Case Expectation

The message is echo'ed back to us.


Case 6.7.3

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xe0a080

Case Expectation

The message is echo'ed back to us.


Case 6.7.4

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0908080

Case Expectation

The message is echo'ed back to us.


Case 6.8.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf888808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.8.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc8480808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.9.1

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0x7f

Case Expectation

The message is echo'ed back to us.


Case 6.9.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xdfbf

Case Expectation

The message is echo'ed back to us.


Case 6.9.3

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.9.4

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.10.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf7bfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.10.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfbbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.10.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfdbfbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.11.1

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xed9fbf

Case Expectation

The message is echo'ed back to us.


Case 6.11.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xee8080

Case Expectation

The message is echo'ed back to us.


Case 6.11.3

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbd

Case Expectation

The message is echo'ed back to us.


Case 6.11.4

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.11.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf4908080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.6

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.7

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x80bf80bf80bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.12.8

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0x808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbe

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc020c120c220c320c420c520c620c720c820c920ca20cb20cc20cd20ce20cf20d020d120d220d320d420d520d620d720d820d920da20db20dc20dd20de20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe020e120e220e320e420e520e620e720e820e920ea20eb20ec20ed20ee20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf020f120f220f320f420f520f620

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf820f920fa20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.13.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc20

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf8808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc80808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.6

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xdf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.7

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xefbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.8

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf7bfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.9

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfbbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.14.10

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfdbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.15.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0e080f08080f8808080fc80808080dfefbff7bfbffbbfbfbffdbfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.16.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfe

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.16.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xff

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.16.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfefeffff

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc0af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf8808080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.17.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc80808080af

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc1bf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe09fbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf08fbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf887bfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.18.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc83bfbfbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xc080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xe08080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf0808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xf880808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.19.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xfc8080808080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.6

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedbe80

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.20.7

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.1

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080edb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.2

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xeda080edbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.3

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbfedb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.4

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedadbfedbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.5

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80edb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.6

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedae80edbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.7

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbfedb080

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.21.8

Up

Case Description

Send a text message with payload which is not valid UTF-8 in one fragment.

Payload: 0xedafbfedbfbf

Case Expectation

The connection is failed immediately, since the payload is not valid UTF-8.


Case 6.22.1

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.3

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf09fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.4

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf09fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.5

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0afbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.6

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0afbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.7

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0bfbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.8

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf0bfbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.9

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf18fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.10

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf18fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.11

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf19fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.12

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf19fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.13

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1afbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.14

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1afbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.15

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1bfbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.16

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf1bfbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.17

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf28fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.18

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf28fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.19

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf29fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.20

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf29fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.21

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2afbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.22

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2afbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.23

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2bfbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.24

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf2bfbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.25

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf38fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.26

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf38fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.27

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf39fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.28

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf39fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.29

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3afbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.30

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3afbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.31

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3bfbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.32

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf3bfbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.22.33

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.22.34

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xf48fbfbf

Case Expectation

The message is echo'ed back to us.


Case 6.23.1

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfb9

Case Expectation

The message is echo'ed back to us.


Case 6.23.2

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfba

Case Expectation

The message is echo'ed back to us.


Case 6.23.3

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbb

Case Expectation

The message is echo'ed back to us.


Case 6.23.4

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbc

Case Expectation

The message is echo'ed back to us.


Case 6.23.5

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbd

Case Expectation

The message is echo'ed back to us.


Case 6.23.6

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbe

Case Expectation

The message is echo'ed back to us.


Case 6.23.7

Up

Case Description

Send a text message with payload which is valid UTF-8 in one fragment.

Payload: 0xefbfbf

Case Expectation

The message is echo'ed back to us.


Case 7.1.1

Up

Case Description

Send a message followed by a close frame

Case Expectation

Echoed message followed by clean close with normal code.


Case 7.1.2

Up

Case Description

Send two close frames

Case Expectation

Clean close with normal code. Second close frame ignored.


Case 7.1.3

Up

Case Description

Send a ping after close message

Case Expectation

Clean close with normal code, no pong.


Case 7.1.4

Up

Case Description

Send text message after sending a close frame.

Case Expectation

Clean close with normal code. Text message ignored.


Case 7.1.5

Up

Case Description

Send message fragment1 followed by close then fragment

Case Expectation

Clean close with normal code.


Case 7.1.6

Up

Case Description

Send 256K message followed by close then a ping

Case Expectation

Case outcome depends on implementation defined close behavior. Message and close frame are sent back to back. If the close frame is processed before the text message write is complete (as can happen in asynchronous processing models) the close frame is processed first and the text message may not be received or may only be partially received.


Case 7.3.1

Up

Case Description

Send a close frame with payload length 0 (no close code, no close reason)

Case Expectation

Clean close with normal code.


Case 7.3.2

Up

Case Description

Send a close frame with payload length 1

Case Expectation

Clean close with protocol error or drop TCP.


Case 7.3.3

Up

Case Description

Send a close frame with payload length 2 (regular close with a code)

Case Expectation

Clean close with normal code.


Case 7.3.4

Up

Case Description

Send a close frame with close code and close reason

Case Expectation

Clean close with normal code.


Case 7.3.5

Up

Case Description

Send a close frame with close code and close reason of maximum length (123)

Case Expectation

Clean close with normal code.


Case 7.3.6

Up

Case Description

Send a close frame with close code and close reason which is too long (124) - total frame payload 126 octets

Case Expectation

Clean close with protocol error code or dropped TCP connection.


Case 7.5.1

Up

Case Description

Send a close frame with invalid UTF8 payload

Case Expectation

Clean close with protocol error or invalid utf8 code or dropped TCP.


Case 7.7.1

Up

Case Description

Send close with valid close code 1000

Case Expectation

Clean close with normal or echoed code


Case 7.7.2

Up

Case Description

Send close with valid close code 1001

Case Expectation

Clean close with normal or echoed code


Case 7.7.3

Up

Case Description

Send close with valid close code 1002

Case Expectation

Clean close with normal or echoed code


Case 7.7.4

Up

Case Description

Send close with valid close code 1003

Case Expectation

Clean close with normal or echoed code


Case 7.7.5

Up

Case Description

Send close with valid close code 1007

Case Expectation

Clean close with normal or echoed code


Case 7.7.6

Up

Case Description

Send close with valid close code 1008

Case Expectation

Clean close with normal or echoed code


Case 7.7.7

Up

Case Description

Send close with valid close code 1009

Case Expectation

Clean close with normal or echoed code


Case 7.7.8

Up

Case Description

Send close with valid close code 1010

Case Expectation

Clean close with normal or echoed code


Case 7.7.9

Up

Case Description

Send close with valid close code 1011

Case Expectation

Clean close with normal or echoed code


Case 7.7.10

Up

Case Description

Send close with valid close code 3000

Case Expectation

Clean close with normal or echoed code


Case 7.7.11

Up

Case Description

Send close with valid close code 3999

Case Expectation

Clean close with normal or echoed code


Case 7.7.12

Up

Case Description

Send close with valid close code 4000

Case Expectation

Clean close with normal or echoed code


Case 7.7.13

Up

Case Description

Send close with valid close code 4999

Case Expectation

Clean close with normal or echoed code


Case 7.9.1

Up

Case Description

Send close with invalid close code 0

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.2

Up

Case Description

Send close with invalid close code 999

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.3

Up

Case Description

Send close with invalid close code 1004

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.4

Up

Case Description

Send close with invalid close code 1005

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.5

Up

Case Description

Send close with invalid close code 1006

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.6

Up

Case Description

Send close with invalid close code 1016

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.7

Up

Case Description

Send close with invalid close code 1100

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.8

Up

Case Description

Send close with invalid close code 2000

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.9.9

Up

Case Description

Send close with invalid close code 2999

Case Expectation

Clean close with protocol error code or drop TCP


Case 7.13.1

Up

Case Description

Send close with close code 5000

Case Expectation

Actual events are undefined by the spec.


Case 7.13.2

Up

Case Description

Send close with close code 65536

Case Expectation

Actual events are undefined by the spec.


Case 9.1.1

Up

Case Description

Send text message message with payload of length 64 * 2**10 (64k).

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.1.2

Up

Case Description

Send text message message with payload of length 256 * 2**10 (256k).

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.1.3

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M).

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.1.4

Up

Case Description

Send text message message with payload of length 4 * 2**20 (4M).

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.1.5

Up

Case Description

Send text message message with payload of length 8 * 2**20 (8M).

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.1.6

Up

Case Description

Send text message message with payload of length 16 * 2**20 (16M).

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.2.1

Up

Case Description

Send binary message message with payload of length 64 * 2**10 (64k).

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.2.2

Up

Case Description

Send binary message message with payload of length 256 * 2**10 (256k).

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.2.3

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M).

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.2.4

Up

Case Description

Send binary message message with payload of length 4 * 2**20 (4M).

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.2.5

Up

Case Description

Send binary message message with payload of length 8 * 2**20 (16M).

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.2.6

Up

Case Description

Send binary message message with payload of length 16 * 2**20 (16M).

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.3.1

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.2

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.3

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.4

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4k.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.5

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 16k.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.6

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64k.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.7

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.8

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1M.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.3.9

Up

Case Description

Send fragmented text message message with message payload of length 4 * 2**20 (8M). Sent out in fragments of 4M.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.4.1

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.2

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.3

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.4

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4k.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.5

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 16k.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.6

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 64k.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.7

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.8

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1M.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.4.9

Up

Case Description

Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 4M.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.5.1

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 64 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.5.2

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 128 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.5.3

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 256 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.5.4

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 512 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.5.5

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 1024 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.5.6

Up

Case Description

Send text message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 2048 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.6.1

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 64 octets.

Case Expectation

Receive echo'ed binary message (with payload as sent).


Case 9.6.2

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 128 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.6.3

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 256 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.6.4

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 512 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.6.5

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 1024 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.6.6

Up

Case Description

Send binary message message with payload of length 1 * 2**20 (1M). Sent out data in chops of 2048 octets.

Case Expectation

Receive echo'ed text message (with payload as sent).


Case 9.7.1

Up

Case Description

Send 1000 text messages of payload size 0 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.


Case 9.7.2

Up

Case Description

Send 1000 text messages of payload size 16 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.


Case 9.7.3

Up

Case Description

Send 1000 text messages of payload size 64 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 60 secs.


Case 9.7.4

Up

Case Description

Send 1000 text messages of payload size 256 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 120 secs.


Case 9.7.5

Up

Case Description

Send 1000 text messages of payload size 1024 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 240 secs.


Case 9.7.6

Up

Case Description

Send 1000 text messages of payload size 4096 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed text messages (with payload as sent). Timeout case after 480 secs.


Case 9.8.1

Up

Case Description

Send 1000 binary messages of payload size 0 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.


Case 9.8.2

Up

Case Description

Send 1000 binary messages of payload size 16 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.


Case 9.8.3

Up

Case Description

Send 1000 binary messages of payload size 64 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 60 secs.


Case 9.8.4

Up

Case Description

Send 1000 binary messages of payload size 256 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 120 secs.


Case 9.8.5

Up

Case Description

Send 1000 binary messages of payload size 1024 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 240 secs.


Case 9.8.6

Up

Case Description

Send 1000 binary messages of payload size 4096 to measure implementation/network RTT (round trip time) / latency.

Case Expectation

Receive echo'ed binary messages (with payload as sent). Timeout case after 480 secs.


Case 10.1.1

Up

Case Description

Send text message with payload of length 65536 auto-fragmented with autoFragmentSize = 1300.

Case Expectation

Receive echo'ed text message (with payload as sent and transmitted frame counts as expected). Clean close with normal code.


Case 12.1.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.1.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.1.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 12.1.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 12.1.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.1.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.2.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.2.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 12.2.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 12.2.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.2.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.3.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.3.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 12.3.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 12.3.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.3.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.4.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.4.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 12.4.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 12.4.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.4.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.5.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 12.5.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 12.5.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 12.5.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 12.5.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use default permessage-deflate offer.

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.1.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.1.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.1.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.1.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.1.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.2.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.2.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.2.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.2.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.2.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.3.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.3.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.3.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.3.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.3.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.4.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.4.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.4.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.4.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.4.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(False, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.5.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.5.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.5.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.5.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.5.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.6.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.6.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.6.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.6.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.6.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 15)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.1

Up

Case Description

Send 1000 compressed messages each of payload size 16, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.7.2

Up

Case Description

Send 1000 compressed messages each of payload size 64, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 60 secs.


Case 13.7.3

Up

Case Description

Send 1000 compressed messages each of payload size 256, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 120 secs.


Case 13.7.4

Up

Case Description

Send 1000 compressed messages each of payload size 1024, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 240 secs.


Case 13.7.5

Up

Case Description

Send 1000 compressed messages each of payload size 4096, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.6

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.7

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.8

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.9

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.10

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 0 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.11

Up

Case Description

Send 1000 compressed messages each of payload size 8192, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.12

Up

Case Description

Send 1000 compressed messages each of payload size 16384, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.13

Up

Case Description

Send 1000 compressed messages each of payload size 32768, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.14

Up

Case Description

Send 1000 compressed messages each of payload size 65536, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.15

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 256 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.16

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 1024 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.17

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 4096 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.


Case 13.7.18

Up

Case Description

Send 1000 compressed messages each of payload size 131072, auto-fragment to 32768 octets. Use permessage-deflate client offers (requestNoContextTakeover, requestMaxWindowBits): [(True, 8), (True, 0), (False, 0)]

Case Expectation

Receive echo'ed messages (with payload as sent). Timeout case after 480 secs.



websocket-client-1.7.0/compliance/fuzzingserver.json000066400000000000000000000002631453274240000227130ustar00rootroot00000000000000{ "url": "ws://localhost:8642", "options": {"failByDrop": false}, "outdir": "./reports/clients", "webport": 8080, "cases": ["*"], "exclude-cases": [], "exclude-agent-cases": {} } websocket-client-1.7.0/compliance/test_fuzzingclient.py000066400000000000000000000035501453274240000234030ustar00rootroot00000000000000import json import traceback import websocket """ test_fuzzingclient.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ SERVER = "ws://127.0.0.1:8642" AGENT = "py-websockets-client" ws = websocket.create_connection(f"{SERVER}/getCaseCount") count = json.loads(ws.recv()) ws.close() case = 0 for case in range(1, count + 1): url = f"{SERVER}/runCase?case={case}&agent={AGENT}" status = websocket.STATUS_NORMAL try: ws = websocket.create_connection(url) while True: opcode, msg = ws.recv_data() if opcode == websocket.ABNF.OPCODE_TEXT: msg.decode("utf-8") if opcode in (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY): ws.send(msg, opcode) except UnicodeDecodeError: # this case is ok. status = websocket.STATUS_PROTOCOL_ERROR except websocket.WebSocketProtocolException: status = websocket.STATUS_PROTOCOL_ERROR except websocket.WebSocketPayloadException: status = websocket.STATUS_INVALID_PAYLOAD except Exception as e: # status = websocket.STATUS_PROTOCOL_ERROR print(traceback.format_exc()) print(e) finally: ws.close(status) print(f"Ran {case} test cases.") url = f"{SERVER}/updateReports?agent={AGENT}" ws = websocket.create_connection(url) websocket-client-1.7.0/docs/000077500000000000000000000000001453274240000157125ustar00rootroot00000000000000websocket-client-1.7.0/docs/Makefile000066400000000000000000000011761453274240000173570ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) websocket-client-1.7.0/docs/make.bat000066400000000000000000000014371453274240000173240ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% :end popd websocket-client-1.7.0/docs/source/000077500000000000000000000000001453274240000172125ustar00rootroot00000000000000websocket-client-1.7.0/docs/source/abnf.rst000066400000000000000000000001711453274240000206510ustar00rootroot00000000000000################## websocket/_abnf.py ################## The _abnf.py file .. automodule:: websocket._abnf :members: websocket-client-1.7.0/docs/source/about.rst000066400000000000000000000007301453274240000210560ustar00rootroot00000000000000##### About ##### The websocket-client project was started in 2011, but experienced a slowdown in development in 2019-2020. The original creator of this project was `liris `_ and the current maintainer (since 2021) is `engn33r `_. The project is in the process of being rejuvenated, so any edits or suggestions are appreciated. No typo is too small for a pull request! See the :ref:`contributing` page for more info. websocket-client-1.7.0/docs/source/app.rst000066400000000000000000000001641453274240000205250ustar00rootroot00000000000000################# websocket/_app.py ################# The _app.py file .. automodule:: websocket._app :members: websocket-client-1.7.0/docs/source/conf.py000066400000000000000000000044401453274240000205130ustar00rootroot00000000000000# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.append(os.path.abspath("../..")) sys.path.append(os.path.abspath("websocket")) # Don't skip __init__, which is skipped by default def skip(app, what, name, obj, would_skip, options): if name == "__init__": return False return would_skip def setup(app): app.connect("autodoc-skip-member", skip) # -- Project information ----------------------------------------------------- project = "websocket-client" copyright = "2023" author = "liris" # The full version, including alpha/beta/rc tags release = "1.7.0" # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.coverage", "sphinx.ext.napoleon", "sphinx.ext.viewcode", "sphinx.ext.autosectionlabel", "sphinx.ext.doctest", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] websocket-client-1.7.0/docs/source/contributing.rst000066400000000000000000000003041453274240000224500ustar00rootroot00000000000000############ Contributing ############ Contributions are welcome! See this project's `contributing guidelines `_ websocket-client-1.7.0/docs/source/core.rst000066400000000000000000000001711453274240000206730ustar00rootroot00000000000000################## websocket/_core.py ################## The _core.py file .. automodule:: websocket._core :members: websocket-client-1.7.0/docs/source/examples.rst000066400000000000000000000674071453274240000216000ustar00rootroot00000000000000######## Examples ######## Creating Your First WebSocket Connection ========================================== If you want to connect to a websocket without writing any code yourself, you can try out the :ref:`getting started` wsdump.py script and the `examples/ `_ directory files. You can create your first custom connection with this library using one of the simple examples below. Note that the first WebSocket example is best for a short-lived connection, while the WebSocketApp example is best for a long-lived connection. **WebSocket example** .. doctest:: sample-connection >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events") >>> ws.send("Hello, Server") 19 >>> print(ws.recv()) echo.websocket.events sponsored by Lob.com >>> ws.close() **WebSocketApp example** .. doctest:: sample-connection >>> import websocket >>> def on_message(wsapp, message): ... print(message) >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", on_message=on_message) >>> wsapp.run_forever() # doctest: +SKIP Debug and Logging Options ========================== When you're first writing your code, you will want to make sure everything is working as you planned. The easiest way to view the verbose connection information is the use ``websocket.enableTrace(True)``. For example, the following example shows how you can verify that the proper Origin header is set. .. code-block:: python :emphasize-lines: 3 import websocket websocket.enableTrace(True) ws = websocket.WebSocket() ws.connect("ws://echo.websocket.events/", origin="testing_websockets.com") ws.send("Hello, Server") print(ws.recv()) ws.close() The output you will see will look something like this: :: --- request header --- GET / HTTP/1.1 Upgrade: websocket Host: echo.websocket.events Origin: testing_websockets.com Sec-WebSocket-Key: GnuCGEiF3OuyRESXiVnsAQ== Sec-WebSocket-Version: 13 Connection: Upgrade ----------------------- --- response header --- HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: websocket Sec-Websocket-Accept: wvhwrjThsVAyr/V4Hzn5tWMSomI= Via: 1.1 vegur ----------------------- ++Sent raw: b'\x81\x8d\xd4\xda9\xee\x9c\xbfU\x82\xbb\xf6\x19\xbd\xb1\xa8O\x8b\xa6' ++Sent decoded: fin=1 opcode=1 data=b'Hello, Server' 19 ++Rcv raw: b'\x81*echo.websocket.events sponsored by Lob.com' ++Rcv decoded: fin=1 opcode=1 data=b'echo.websocket.events sponsored by Lob.com' echo.websocket.events sponsored by Lob.com ++Sent raw: b'\x88\x82\xc9\x8c\x14\x99\xcad' ++Sent decoded: fin=1 opcode=8 data=b'\x03\xe8' Using websocket-client with "with" statements ============================================== It is possible to use "with" statements, as outlined in PEP 343, to help manage the closing of WebSocket connections after a message is received. Below is one example of this being done with a short-lived connection: **Short-lived WebSocket using "with" statement** .. doctest:: sample-connection >>> from contextlib import closing >>> from websocket import create_connection >>> with closing(create_connection("wss://testnet-explorer.binance.org/ws/block")) as conn: ... print(conn.recv()) # doctest: +SKIP # Connection is now closed Connection Options =================== After you can establish a basic WebSocket connection, customizing your connection using specific options is the next step. Fortunately, this library provides many options you can configure, such as: * "Host" header value * "Cookie" header value * "Origin" header value * WebSocket subprotocols * Custom headers * SSL or hostname verification * Timeout value For a more detailed list of the options available for the different connection methods, check out the source code comments for each: * `WebSocket().connect() option docs `_ * Related: `WebSocket.create_connection() option docs `_ * `WebSocketApp() option docs `_ * Related: `WebSocketApp.run_forever docs `_ Setting Common Header Values -------------------------------- To modify the ``Host``, ``Origin``, ``Cookie``, or ``Sec-WebSocket-Protocol`` header values of the WebSocket handshake request, pass the ``host``, ``origin``, ``cookie``, or ``subprotocols`` options to your WebSocket connection. The first two examples show the Host, Origin, and Cookies headers being set, while the Sec-WebSocket-Protocol header is set separately in the following example. For debugging, remember that it is helpful to enable :ref:`Debug and Logging Options`. **WebSocket common headers example** .. doctest:: headers >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events", cookie="chocolate", ... origin="testing_websockets-client.com", host="echo.websocket.events") **WebSocketApp common headers example** .. doctest:: headers >>> import websocket >>> def on_message(wsapp, message): ... print(message) >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", ... cookie="chocolate", on_message=on_message) >>> wsapp.run_forever(origin="testing_websockets.com", host="127.0.0.1") # doctest: +SKIP **WebSocket subprotocols example** Use this to specify STOMP, WAMP, MQTT, or other values of the "Sec-WebSocket-Protocol" header. Be aware that websocket-client does not include support for these protocols, so your code must handle the data sent over the WebSocket connection. .. doctest:: subprotocols >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("wss://ws.kraken.com", subprotocols=["mqtt"]) **WebSocketApp subprotocols example** .. doctest:: subprotocols >>> import websocket >>> def on_message(wsapp, message): ... print(message) >>> wsapp = websocket.WebSocketApp("wss://ws.kraken.com", ... subprotocols=["STOMP"], on_message=on_message) >>> wsapp.run_forever() # doctest: +SKIP Suppress Origin Header ------------------------- There is a special ``suppress_origin`` option that can be used to remove the ``Origin`` header from connection handshake requests. The below examples illustrate how this can be used. For debugging, remember that it is helpful to enable :ref:`Debug and Logging Options`. **WebSocket suppress origin example** .. doctest:: suppress-origin >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events", suppress_origin=True) **WebSocketApp suppress origin example** .. doctest:: suppress-origin >>> import websocket >>> def on_message(wsapp, message): ... print(message) >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", ... on_message=on_message) >>> wsapp.run_forever(suppress_origin=True) # doctest: +SKIP Setting Custom Header Values -------------------------------- Setting custom header values, other than ``Host``, ``Origin``, ``Cookie``, or ``Sec-WebSocket-Protocol`` (which are addressed above), in the WebSocket handshake request is similar to setting common header values. Use the ``header`` option to provide custom header values in a list or dict. For debugging, remember that it is helpful to enable :ref:`Debug and Logging Options`. There is no built-in support for "Sec-WebSocket-Extensions" header values as defined in RFC 7692. **WebSocket custom headers example** .. doctest:: custom-headers >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events", ... header={"CustomHeader1":"123", "NewHeader2":"Test"}) **WebSocketApp custom headers example** .. doctest:: custom-headers >>> import websocket >>> def on_message(wsapp, message): ... print(message) >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", ... header={"CustomHeader1":"123", "NewHeader2":"Test"}, on_message=on_message) >>> wsapp.run_forever() # doctest: +SKIP Disabling SSL or Hostname Verification --------------------------------------- See the relevant :ref:`FAQ` page for instructions. Using a Custom Class -------------------------------- You can also write your own class for the connection, if you want to handle the nitty-gritty connection details yourself. .. doctest:: custom-class >>> import socket >>> from websocket import create_connection, WebSocket >>> class MyWebSocket(WebSocket): ... def recv_frame(self): ... frame = super().recv_frame() ... print('yay! I got this frame: ', frame) ... return frame >>> ws = create_connection("ws://echo.websocket.events/", ... sockopt=((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),), class_=MyWebSocket) Setting Timeout Value -------------------------------- The _socket.py file contains the functions ``setdefaulttimeout()`` and ``getdefaulttimeout()``. These two functions set the global ``_default_timeout`` value, which sets the socket timeout value (in seconds). These two functions should not be confused with the similarly named ``settimeout()`` and ``gettimeout()`` functions found in the _core.py file. With WebSocketApp, the ``run_forever()`` function gets assigned the timeout `from getdefaulttimeout() `_. When the timeout value is reached, the exception WebSocketTimeoutException is triggered by the _socket.py ``send()`` and ``recv()`` functions. Additional timeout values can be found in other locations in this library, including the ``close()`` function of the WebSocket class and the ``create_connection()`` function of the WebSocket class. The WebSocket timeout example below shows how an exception is triggered after no response is received from the server after 5 seconds. **WebSocket timeout example** .. doctest:: timeout-example >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events", timeout=5) >>> # ws.send("Hello, Server") # Commented out to trigger WebSocketTimeoutException >>> print(ws.recv()) # doctest: +SKIP # Program should end with a WebSocketTimeoutException The WebSocketApp timeout example works a bit differently than the WebSocket example. Because WebSocketApp handles long-lived connections, it does not timeout after a certain amount of time without receiving a message. Instead, a timeout is triggered if no connection response is received from the server after the timeout interval (5 seconds in the example below). **WebSocketApp timeout example** .. doctest:: timeout-example >>> import websocket >>> def on_error(wsapp, err): ... print("EXAMPLE error encountered: ", err) >>> websocket.setdefaulttimeout(5) >>> wsapp = websocket.WebSocketApp("ws://nexus-websocket-a.intercom.io", ... on_error=on_error) >>> wsapp.run_forever() # doctest: +SKIP # Program should print a "timed out" error message Connecting through a proxy ---------------------------- websocket-client supports proxied connections. The supported proxy protocols are HTTP, SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h. If you want to route DNS requests through the proxy, use SOCKS4a or SOCKS5h. The proxy protocol should be specified in lowercase to the ``proxy_type`` parameter. The example below shows how to connect through a HTTP or SOCKS proxy. Proxy authentication is supported with the ``http_proxy_auth`` parameter, which should be a tuple of the username and password. Be aware that the current implementation of websocket-client uses the "CONNECT" method for HTTP proxies (though soon the HTTP proxy handling will use the same ``python_socks`` library currently enabled only for SOCKS proxies), and the HTTP proxy server must allow the "CONNECT" method. For example, the squid HTTP proxy only allows the "CONNECT" method `on HTTPS ports `_ by default. You may encounter problems if using SSL/TLS with your proxy. **WebSocket HTTP proxy with authentication example** :: import websocket ws = websocket.WebSocket() ws.connect("ws://echo.websocket.events", http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http", http_proxy_auth=("username", "password123")) ws.send("Hello, Server") print(ws.recv()) ws.close() **WebSocket SOCKS4 (or SOCKS5) proxy example** :: import websocket ws = websocket.WebSocket() ws.connect("ws://echo.websocket.events", http_proxy_host="192.168.1.18", http_proxy_port="4444", proxy_type="socks4") ws.send("Hello, Server") print(ws.recv()) ws.close() **WebSocketApp proxy example** :: import websocket ws = websocket.WebSocketApp("ws://echo.websocket.events") wsapp.run_forever(proxy_type="socks5", http_proxy_host=proxy_ip, http_proxy_auth=(proxy_username, proxy_password)) Connecting with Custom Sockets -------------------------------- You can also connect to a WebSocket server hosted on a specific socket using the ``socket`` option when creating your connection. Below is an example of using a unix domain socket. :: import socket from websocket import create_connection my_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) my_socket.connect("/path/to/my/unix.socket") ws = create_connection("ws://localhost/", # Dummy URL socket = my_socket, sockopt=((socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),)) Other socket types can also be used. The following example is for a AF_INET (IP address) socket. :: import socket from websocket import create_connection my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_socket.bind(("172.18.0.1", 3002)) my_socket.connect() ws = create_connection("ws://127.0.0.1/", # Dummy URL socket = my_socket) Post-connection Feature Summary ------------------------------- `Autobahn|TestSuite `_ is an independent automated test suite to verify the compliance of WebSocket implementations. Running the test suite against this library will produce a summary report of the conformant features that have been implemented. A recently-run autobahn report (available as an .html file) is available in the /compliance directory. Ping/Pong Usage -------------------------------- The WebSocket specification defines `ping `_ and `pong `_ message opcodes as part of the protocol. These can serve as a way to keep a connection active even if data is not being transmitted. Pings may be sent in either direction. If the client receives a ping, a pong reply will be automatically sent. However, if a blocking event is happening, there may be some issues with ping/pong. Below are examples of how ping and pong can be sent by this library. You can get additional debugging information by using `Wireshark `_ to view the ping and pong messages being sent. In order for Wireshark to identify the WebSocket protocol properly, it should observe the initial HTTP handshake and the HTTP 101 response in cleartext (without encryption) - otherwise the WebSocket messages may be categorized as TCP or TLS messages. For debugging, remember that it is helpful to enable :ref:`Debug and Logging Options`. **WebSocket ping/pong example** This example is best for a quick test where you want to check the effect of a ping, or where situations where you want to customize when the ping is sent. .. doctest:: ping-pong >>> import websocket >>> websocket.enableTrace(True) >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events") >>> ws.ping() >>> ws.ping("This is an optional ping payload") >>> ws.close() **WebSocketApp ping/pong example** This example, and ``run_forever()`` in general, is better for long-lived connections. In this example, if a ping is received and a pong is sent in response, then the client is notified via ``on_ping()``. Further, a ping is transmitted every 60 seconds. If a pong is received, then the client is notified via ``on_pong()``. If no pong is received within 10 seconds, then ``run_forever()`` will exit with a ``WebSocketTimeoutException``. .. doctest:: ping-pong >>> import websocket >>> def on_message(wsapp, message): ... print(message) >>> def on_ping(wsapp, message): ... print("Got a ping! A pong reply has already been automatically sent.") >>> def on_pong(wsapp, message): ... print("Got a pong! No need to respond") >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", ... on_message=on_message, on_ping=on_ping, on_pong=on_pong) >>> wsapp.run_forever(ping_interval=60, ping_timeout=10, ping_payload="This is an optional ping payload") # doctest: +SKIP Sending Connection Close Status Codes -------------------------------------- RFC6455 defines `various status codes `_ that can be used to identify the reason for a close frame ending a connection. These codes are defined in the websocket/_abnf.py file. To view the code used to close a connection, you can :ref:`enable logging` to view the status code information. You can also specify your own status code in the .close() function, as seen in the examples below. Specifying a custom status code is necessary when using the custom status code values between 3000-4999. **WebSocket sending close() status code example** .. doctest:: close-status >>> import websocket >>> websocket.enableTrace(True) >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events") >>> ws.send("Hello, Server") 19 >>> print(ws.recv()) echo.websocket.events sponsored by Lob.com >>> ws.close(websocket.STATUS_PROTOCOL_ERROR) # doctest: +SKIP # Alternatively, use ws.close(status=1002) **WebSocketApp sending close() status code example** .. doctest:: close-status >>> import websocket >>> websocket.enableTrace(True) >>> def on_message(wsapp, message): ... print(message) ... wsapp.close(status=websocket.STATUS_PROTOCOL_ERROR) # Alternatively, use wsapp.close(status=1002) >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", on_message=on_message) >>> wsapp.run_forever(skip_utf8_validation=True) # doctest: +SKIP Receiving Connection Close Status Codes ----------------------------------------- The RFC6455 spec states that it is optional for a server to send a close status code when closing a connection. The RFC refers to these codes as WebSocket Close Code Numbers, and their meanings are described in the RFC. It is possible to view this close code, if it is being sent, to understand why the connection is being close. One option to view the code is to :ref:`enable logging` to view the status code information. If you want to use the close status code in your program, examples are shown below for how to do this. **WebSocket receiving close status code example** .. doctest:: close-status >>> import websocket >>> import struct >>> websocket.enableTrace(True) >>> ws = websocket.WebSocket() >>> ws.connect("wss://tsock.us1.twilio.com/v3/wsconnect") >>> ws.send("Hello") 11 >>> resp_opcode, msg = ws.recv_data() >>> print("Response opcode: " + str(resp_opcode)) # doctest: +SKIP >>> if resp_opcode == 8 and len(msg) >= 2: ... print("Response close code: " + str(struct.unpack("!H", msg[0:2])[0])) # doctest: +SKIP ... print("Response message: " + str(msg[2:])) # doctest: +SKIP ... else: ... print("Response message: " + str(msg)) # doctest: +SKIP **WebSocketApp receiving close status code example** .. doctest:: close-status >>> import websocket >>> websocket.enableTrace(True) >>> def on_close(wsapp, close_status_code, close_msg): ... # Because on_close was triggered, we know the opcode = 8 ... print("on_close args:") ... if close_status_code or close_msg: ... print("close status code: " + str(close_status_code)) ... print("close message: " + str(close_msg)) >>> def on_open(wsapp): ... wsapp.send("Hello") >>> wsapp = websocket.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect", on_close=on_close, on_open=on_open) >>> wsapp.run_forever() # doctest: +SKIP Customizing frame mask -------------------------------- WebSocket frames use masking with a random value to add entropy. The masking value in websocket-client is normally set using os.urandom in the websocket/_abnf.py file. However, this value can be customized as you wish. One use case, outlined in `issue #473 `_, is to set the masking key to a null value to make it easier to decode the messages being sent and received. This is effectively the same as "removing" the mask, though the mask cannot be fully "removed" because it is a part of the WebSocket frame. Tools such as Wireshark can automatically remove masking from payloads to decode the payload message, but it may be easier to skip the demasking step in your custom project. **WebSocket custom masking key code example** .. doctest:: frame-mask >>> import websocket >>> websocket.enableTrace(True) >>> def zero_mask_key(_): ... return "\x00\x00\x00\x00" >>> ws = websocket.WebSocket() >>> ws.set_mask_key(zero_mask_key) >>> ws.connect("ws://echo.websocket.events") >>> ws.send("Hello, Server") # doctest: +SKIP >>> print(ws.recv()) # doctest: +SKIP >>> ws.close() **WebSocketApp custom masking key code example** .. doctest:: frame-mask >>> import websocket >>> websocket.enableTrace(True) >>> def zero_mask_key(_): ... return "\x00\x00\x00\x00" >>> def on_message(wsapp, message): ... print(message) >>> wsapp = websocket.WebSocketApp("wss://testnet-explorer.binance.org/ws/block", on_message=on_message, get_mask_key=zero_mask_key) >>> wsapp.run_forever() # doctest: +SKIP Customizing opcode -------------------------------- WebSocket frames contain an opcode, which defines whether the frame contains text data, binary data, or is a special frame. The different opcode values are defined in `RFC6455 section 11.8 `_. Although the text opcode, 0x01, is the most commonly used value, the websocket-client library makes it possible to customize which opcode is used. **WebSocket custom opcode code example** .. doctest:: custom-opcode >>> import websocket >>> websocket.enableTrace(True) >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events") >>> ws.send("Hello, Server", websocket.ABNF.OPCODE_TEXT) # doctest: +SKIP >>> print(ws.recv()) # doctest: +SKIP >>> ws.send("This is a ping", websocket.ABNF.OPCODE_PING) # doctest: +SKIP >>> ws.close() **WebSocketApp custom opcode code example** The WebSocketApp class contains different functions to handle different message opcodes. For instance, on_close, on_ping, on_pong, on_cont_message. One drawback of the current implementation (as of May 2021) is the lack of binary support for WebSocketApp, as noted by `issue #351 `_. .. doctest:: custom-opcode >>> import websocket >>> websocket.enableTrace(True) >>> def on_open(wsapp): ... wsapp.send("Hello") >>> def on_message(ws, message): ... print(message) ... ws.send("Send a ping", websocket.ABNF.OPCODE_PING) >>> def on_pong(wsapp, message): ... print("Got a pong! No need to respond") >>> wsapp = websocket.WebSocketApp("ws://echo.websocket.events", on_open=on_open, on_message=on_message, on_pong=on_pong) >>> wsapp.run_forever() # doctest: +SKIP Dispatching Multiple WebSocketApps ================================== You can use an asynchronous dispatcher such as `rel `_ to run multiple WebSocketApps in the same application without resorting to threads. **WebSocketApp asynchronous dispatcher code example** .. doctest:: multiple-dispatchers >>> import websocket, rel >>> addr = "wss://api.gemini.com/v1/marketdata/%s" >>> for symbol in ["BTCUSD", "ETHUSD", "ETHBTC"]: ... ws = websocket.WebSocketApp(addr % (symbol,), on_message=lambda w, m : print(m)) ... ws.run_forever(dispatcher=rel, reconnect=3) # doctest: +SKIP >>> rel.signal(2, rel.abort) # Keyboard Interrupt # doctest: +SKIP >>> rel.dispatch() # doctest: +SKIP README Examples ========================= The examples are found in the README and are copied here for sphinx doctests to verify they run without errors. **Long-lived Connection** .. doctest:: long-lived-connection >>> import websocket >>> import _thread >>> import time >>> import rel >>> def on_message(ws, message): ... print(message) >>> def on_error(ws, error): ... print(error) >>> def on_close(ws, close_status_code, close_msg): ... print("### closed ###") >>> def on_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 unexpectedly # doctest: +SKIP >>> rel.signal(2, rel.abort) # Keyboard Interrupt >>> rel.dispatch() # doctest: +SKIP **Short-lived Connection** .. doctest:: short-lived-connection >>> from websocket import create_connection >>> ws = create_connection("ws://echo.websocket.events/") >>> print(ws.recv()) echo.websocket.events sponsored by Lob.com >>> print("Sending 'Hello, World'...") Sending 'Hello, World'... >>> ws.send("Hello, World") 18 >>> print("Sent") Sent >>> print("Receiving...") Receiving... >>> result = ws.recv() >>> print("Received '%s'" % result) Received ... >>> ws.close() Real-world Examples ========================= Other projects that depend on websocket-client may be able to illustrate more complex use cases for this library. A list of 600+ dependent projects is found `on libraries.io `_, and a few of the projects using websocket-client are listed below: - `https://github.com/apache/airflow `_ - `https://github.com/docker/docker-py `_ - `https://github.com/scrapinghub/slackbot `_ - `https://github.com/slackapi/python-slack-sdk `_ - `https://github.com/wee-slack/wee-slack `_ - `https://github.com/aluzzardi/wssh/ `_ - `https://github.com/llimllib/limbo `_ - `https://github.com/miguelgrinberg/python-socketio `_ - `https://github.com/invisibleroads/socketIO-client `_ - `https://github.com/s4w3d0ff/python-poloniex `_ - `https://github.com/Ape/samsungctl `_ - `https://github.com/xchwarze/samsung-tv-ws-api `_ - `https://github.com/andresriancho/websocket-fuzzer `_ websocket-client-1.7.0/docs/source/exceptions.rst000066400000000000000000000002271453274240000221260ustar00rootroot00000000000000######################## websocket/_exceptions.py ######################## The _exceptions.py file .. automodule:: websocket._exceptions :members: websocket-client-1.7.0/docs/source/faq.rst000066400000000000000000000264471453274240000205300ustar00rootroot00000000000000### FAQ ### What about Python 2 support? ============================== Release 0.59.0 was the last main release supporting Python 2. All future releases 1.X.X and beyond will only support Python 3. Why is this library slow? =========================== The ``send`` and ``validate_utf8`` methods are very slow in pure Python. You can disable UTF8 validation in this library (and receive a performance enhancement) with the ``skip_utf8_validation`` parameter. 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 the ``send`` process. Numpy used to be a suggested alternative, but `issue #687 `_ found it didn't help. How to troubleshoot an unclear callback error? =================================================== To get more information about a callback error, you can specify a custom ``on_error()`` function that raises errors to provide more information. Sample code of such a solution is shown below, although the example URL provided will probably not trigger an error under normal circumstances. `Issue #377 `_ discussed this topic previously. .. doctest:: print-callback >>> import websocket >>> >>> def on_message(ws, message): ... print(message) >>> def on_error(wsapp, err): ... print("Got a an error: ", err) >>> wsapp = websocket.WebSocketApp("ws://echo.websocket.events/", ... on_message = on_message, ... on_error=on_error) >>> wsapp.run_forever() # doctest: +SKIP How to solve the "connection is already closed" error? =========================================================== The WebSocketConnectionClosedException, which returns the message "Connection is already closed.", occurs when a WebSocket function such as ``send()`` or ``recv()`` is called but the WebSocket connection is already closed. One way to handle exceptions in Python is by using `a try/except `_ statement, which allows you to control what your program does if the WebSocket connection is closed when you try to use it. In order to properly carry out further functions with your WebSocket connection after the connection has closed, you will need to reconnect the WebSocket, using ``connect()`` or ``create_connection()`` (from the _core.py file). The WebSocketApp ``run_forever()`` function automatically tries to reconnect when the connection is lost if a dispatcher parameter is provided to the ``run_forever()`` function. What's going on with the naming of this library? ================================================== To install this library, you use ``pip3 install websocket-client``, while ``import websocket`` imports this library, and PyPi lists the package as ``websocket_client``. Why is it so confusing? To see the original issue about the choice of ``import websocket``, see `issue #60 `_ and to read about websocket-client vs. websocket_client, see `issue #147 `_ Is WebSocket Compression using the permessage-deflate extension supported? ============================================================================ No, `RFC 7692 `_ for WebSocket Compression is unfortunately not supported by the websocket-client library at this time. You can view the currently supported WebSocket features in the latest autobahn compliance HTML report, found under the `compliance folder. `_ If you use the ``Sec-WebSocket-Extensions: permessage-deflate`` header with websocket-client, you will probably encounter errors, such as the ones described in `issue #314. `_ I get the error 'utf8' codec can't decode byte 0x81 in position 0 ============================================================================ This error is caused when you receive a character that is not a UTF-8 character, so the UTF-8 decoding fails. You can set `skip_utf8_validation` to false, but if this does not work, you can change the encoding to ISO-8859-1 which was a workaround suggested in [issue 481](https://github.com/websocket-client/websocket-client/issues/481#issuecomment-1112506666). If a connection is re-established after getting disconnected, does the new connection continue where the previous one dropped off? ======================================================================================================================================= The answer to this question depends on how the WebSocket server handles new connections. If the server keeps a list of recently dropped WebSocket connection sessions, then it may allow you to recontinue your WebSocket connection where you left off before disconnecting. However, this requires extra effort from the server and may create security issues. For these reasons it is rare to encounter such a WebSocket server. The server would need to identify each connecting client with authentication and keep track of which data was received using a method like TCP's SYN/ACK. That's a lot of overhead for a lightweight protocol! Both HTTP and WebSocket connections use TCP sockets, and when a new WebSocket connection is created, it uses a new TCP socket. Therefore, at the TCP layer, the default behavior is to give each WebSocket connection a separate TCP socket. This means the re-established connection after a disconnect is the same as a completely new connection. Another way to think about this is: what should the server do if you create two WebSocket connections from the same client to the same server? The easiest solution for the server is to treat each connection separately, unless the WebSocket uses an authentication method to identify individual clients connecting to the server. What is the difference between recv_frame(), recv_data_frame(), and recv_data()? ================================================================================== This is explained in `issue #688 `_. This information is useful if you do NOT want to use ``run_forever()`` but want to have similar functionality. In short, ``recv_data()`` is the recommended choice and you will need to manage ping/pong on your own, while ``run_forever()`` handles ping/pong by default. How to disable ssl cert verification? ======================================= Set the sslopt to ``{"cert_reqs": ssl.CERT_NONE}``. The same sslopt argument is provided for all examples seen below. **WebSocketApp example** .. doctest:: disable-ssl-verification >>> import websocket, ssl >>> ws = websocket.WebSocketApp("wss://echo.websocket.events") >>> ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) # doctest: +SKIP **create_connection example** .. doctest:: disable-ssl-verification >>> import websocket, ssl >>> ws = websocket.create_connection("wss://echo.websocket.events", ... sslopt={"cert_reqs": ssl.CERT_NONE}) **WebSocket example** .. doctest:: disable-ssl-verification >>> import websocket, ssl >>> ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) >>> ws.connect("wss://echo.websocket.events") How to disable hostname verification? ======================================= Please set sslopt to ``{"check_hostname": False}``. (since v0.18.0) **WebSocketApp example** .. doctest:: disable-hostname-verification >>> import websocket >>> ws = websocket.WebSocketApp("wss://echo.websocket.events") >>> ws.run_forever(sslopt={"check_hostname": False}) # doctest: +SKIP **create_connection example** .. doctest:: disable-hostname-verification >>> import websocket >>> ws = websocket.create_connection("wss://echo.websocket.events", ... sslopt={"check_hostname": False}) **WebSocket example** .. doctest:: disable-hostname-verification >>> import websocket >>> ws = websocket.WebSocket(sslopt={"check_hostname": False}) >>> ws.connect("wss://echo.websocket.events") What else can I do with sslopts? ============================================================================ The ``sslopt`` parameter is a dictionary to which the following keys can be assigned: * ``certfile``, ``keyfile``, ``password`` (see `SSLContext.load_cert_chain `_) * ``ecdh_curve`` (see `SSLContext.set_ecdh_curve `_) * ``ciphers`` (see `SSLContext.set_ciphers `_) * ``cert_reqs`` (see `SSLContext.verify_mode `_) * ``ssl_version`` (see `SSLContext.protocol `_) * ``ca_certs``, ``ca_cert_path`` (see `SSLContext.load_verify_locations `_) * ``check_hostname`` (see `SSLContext.check_hostname `_) * ``server_hostname``, ``do_handshake_on_connect``, ``suppress_ragged_eofs`` (see `SSLContext.wrap_socket `_) If any other SSL options are required, they can be used by creating a custom SSLContext from the python SSL library and then passing that in as the value of the ``context`` key. (since v1.2.2) For example, if you wanted to load all of the default CA verification certificates, but also add your own additional custom CAs (of which the certs are located in the file "my_extra_CAs.cer"), you could do this: .. doctest:: sslopts >>> import ssl >>> my_context = ssl.create_default_context() >>> my_context.load_verify_locations('my_extra_CAs.cer') # doctest: +SKIP >>> ws.run_forever(sslopt={'context': my_context}) # doctest: +SKIP Note that when passing in a custom ``context``, all of the other context-related options are ignored. In other words, only the ``server_hostname``, ``do_handshake_on_connect``, and ``suppress_ragged_eofs`` options can be used in conjunction with ``context``. How to enable `SNI `_? ============================================================================ SNI support is available for Python 2.7.9+ and 3.2+. It will be enabled automatically whenever possible. Why don't I receive all the server's message(s)? =================================================== Depending on how long your connection exists, it can help to ping the server to keep the connection alive. See `issue #200 `_ for possible solutions. Using Subprotocols ==================== The WebSocket RFC `outlines the usage of subprotocols `_. The subprotocol can be specified as in the example below: .. doctest:: subprotocols >>> import websocket >>> ws = websocket.create_connection("ws://echo.websocket.events", subprotocols=["binary", "base64"]) # doctest: +SKIP websocket-client-1.7.0/docs/source/getting_started.rst000066400000000000000000000037371453274240000231450ustar00rootroot00000000000000############### Getting Started ############### The quickest way to get started with this library is to use the `_wsdump.py script `_. For an easy example, run the following: :: python _wsdump.py ws://echo.websocket.events/ -t "hello world" The above command will provide you with an interactive terminal to communicate with the echo.websocket.events server. This server will echo back any message you send it. The wsdump.py script has many additional options too, so it's a great way to try using this library without writing any custom code. The output of ``python wsdump.py -h`` is seen below, showing the additional options available. :: python wsdump.py -h usage: wsdump.py [-h] [-p PROXY] [-v [VERBOSE]] [-n] [-r] [-s [SUBPROTOCOLS [SUBPROTOCOLS ...]]] [-o ORIGIN] [--eof-wait EOF_WAIT] [-t TEXT] [--timings] [--headers HEADERS] ws_url WebSocket Simple Dump Tool positional arguments: ws_url websocket url. ex. ws://echo.websocket.events/ optional arguments: -h, --help show this help message and exit -p PROXY, --proxy PROXY proxy url. ex. http://127.0.0.1:8080 -v [VERBOSE], --verbose [VERBOSE] set verbose mode. If set to 1, show opcode. If set to 2, enable to trace websocket module -n, --nocert Ignore invalid SSL cert -r, --raw raw output -s [SUBPROTOCOLS [SUBPROTOCOLS ...]], --subprotocols [SUBPROTOCOLS [SUBPROTOCOLS ...]] Set subprotocols -o ORIGIN, --origin ORIGIN Set origin --eof-wait EOF_WAIT wait time(second) after 'EOF' received. -t TEXT, --text TEXT Send initial text --timings Print timings in seconds --headers HEADERS Set custom headers. Use ',' as separator websocket-client-1.7.0/docs/source/index.rst000066400000000000000000000010041453274240000210460ustar00rootroot00000000000000########################################### Welcome to websocket-client's documentation ########################################### .. toctree:: :maxdepth: 2 :caption: Introduction: installation getting_started examples threading faq contributing about .. toctree:: :maxdepth: 2 :caption: Comments Embedded in Code: abnf app core exceptions logging socket url Indices and tables ================== * :ref:`genindex` * :ref:`modindex` .. * :ref:`search` websocket-client-1.7.0/docs/source/installation.rst000066400000000000000000000002261453274240000224450ustar00rootroot00000000000000############ Installation ############ You can use either ``python3 setup.py install`` or ``pip3 install websocket-client`` to install this library. websocket-client-1.7.0/docs/source/logging.rst000066400000000000000000000002101453274240000213630ustar00rootroot00000000000000##################### websocket/_logging.py ##################### The _logging.py file .. automodule:: websocket._logging :members: websocket-client-1.7.0/docs/source/requirements.txt000066400000000000000000000000421453274240000224720ustar00rootroot00000000000000Sphinx>=3.4 sphinx_rtd_theme>=0.5 websocket-client-1.7.0/docs/source/socket.rst000066400000000000000000000002031453274240000212270ustar00rootroot00000000000000#################### websocket/_socket.py #################### The _socket.py file .. automodule:: websocket._socket :members: websocket-client-1.7.0/docs/source/threading.rst000066400000000000000000000140371453274240000217160ustar00rootroot00000000000000######### Threading ######### Importance of enable_multithread ====================================== The ``enable_multithread`` variable should be set to ``True`` when working with multiple threads. If ``enable_multithread`` is not set to ``True``, websocket-client will act asynchronously and not be thread safe. This variable should be enabled by default starting with the 1.1.0 release, but had a default value of ``False`` in older versions. See issues `#591 `_ and `#507 `_ for related issues. asyncio library usage ======================= Issue `#496 `_ indicates that websocket-client is not compatible with asyncio. The `engine-io project `_, which is used in a popular socket-io client, specifically uses websocket-client as a dependency only in places where asyncio is not used. If asyncio is an important part of your project, you might consider using another websockets library. However, some simple use cases, such as asynchronously receiving data, may be a place to use asyncio. Here is one snippet showing how asynchronous listening might be implemented. :: async def mylisten(ws): result = await asyncio.get_event_loop().run_in_executor(None, ws.recv) return result threading library usage ========================== The websocket-client library has some built-in threading support provided by the ``threading`` library. You will see ``import threading`` in some of this project's code. The `echoapp_client.py example `_ is a good illustration of how ``threading`` can be used in the websocket-client library. Another example is found in `an external site's documentation `_, which demonstrates using the _thread library, which is lower level than the threading library. Possible issues with threading ================================== Further investigation into using the ``threading`` module is seen in issue `#612 `_ which illustrates one situation where using the threading module can impact the observed behavior of this library. The first code example below does not trigger the ``on_close()`` function, but the second code example does trigger the ``on_close()`` function. The highlighted rows show the lines added exclusively in the second example. This threading approach is identical to the `echoapp_client.py example `_. However, further testing found that some WebSocket servers, such as ws://echo.websocket.events, do not trigger the ``on_close()`` function. **NOT working on_close() example, without threading** :: import websocket websocket.enableTrace(True) def on_open(ws): ws.send("hi") def on_message(ws, message): print(message) ws.close() print("Message received...") def on_close(ws, close_status_code, close_msg): print(">>>>>>CLOSED") wsapp = websocket.WebSocketApp("wss://api.bitfinex.com/ws/1", on_open=on_open, on_message=on_message, on_close=on_close) wsapp.run_forever() **Working on_close() example, with threading** .. code-block:: python :emphasize-lines: 2,10,15 import websocket import threading websocket.enableTrace(True) def on_open(ws): ws.send("hi") def on_message(ws, message): def run(*args): print(message) ws.close() print("Message received...") threading.Thread(target=run).start() def on_close(ws, close_status_code, close_msg): print(">>>>>>CLOSED") wsapp = websocket.WebSocketApp("wss://api.bitfinex.com/ws/1", on_open=on_open, on_message=on_message, on_close=on_close) wsapp.run_forever() Another example of code that does not trigger `on_close` is below. The fix is to use a timer. **NOT working on_close() example, with sleep delay** .. code-block:: python :emphasize-lines: 11 import websocket from threading import Thread import sys import time def on_close(ws, close_status_code, close_msg): print("### closed ###") def on_message(ws, message): print(message) time.sleep(2) if __name__ == "__main__": websocket.enableTrace(True) if len(sys.argv) < 2: host = "ws://echo.websocket.events/" else: host = sys.argv[1] ws = websocket.WebSocketApp(host, on_message=on_message, on_close=on_close) Thread(target=ws.run_forever).start() time.sleep(1) ws.close() **Working on_close() example, with threading delay** .. code-block:: python :emphasize-lines: 11,12 import websocket from threading import Thread import sys import time def on_close(ws, close_status_code, close_msg): print("### closed ###") def on_message(ws, message): print(message) timer = threading.Timer(2, ws.close) timer.start() if __name__ == "__main__": websocket.enableTrace(True) if len(sys.argv) < 2: host = "ws://echo.websocket.events/" else: host = sys.argv[1] ws = websocket.WebSocketApp(host, on_message=on_message, on_close=on_close) Thread(target=ws.run_forever).start() time.sleep(1) ws.close() In part because threading is hard, but also because this project has (until recently) lacked any threading documentation, there are many issues on this topic, including: - `#562 `_ - `#580 `_ - `#591 `_ websocket-client-1.7.0/docs/source/url.rst000066400000000000000000000001641453274240000205470ustar00rootroot00000000000000################# websocket/_url.py ################# The _url.py file .. automodule:: websocket._url :members: websocket-client-1.7.0/examples/000077500000000000000000000000001453274240000166005ustar00rootroot00000000000000websocket-client-1.7.0/examples/echo_client.py000066400000000000000000000005261453274240000214310ustar00rootroot00000000000000import websocket if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.create_connection("ws://echo.websocket.events/") ws.recv() print("Sending 'Hello, World'...") ws.send("Hello, World") print("Sent") print("Receiving...") result = ws.recv() print(f"Received '{result}'") ws.close() websocket-client-1.7.0/examples/echoapp_client.py000066400000000000000000000016401453274240000221300ustar00rootroot00000000000000import sys import time from threading import Thread import websocket def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws, close_status_code, close_msg): print("### closed ###") def on_open(ws): def run(*args): for i in range(3): # send the message, then wait # so thread doesn't exit and socket # isn't closed ws.send("Hello %d" % i) time.sleep(1) time.sleep(1) ws.close() print("Thread terminating...") Thread(target=run).start() if __name__ == "__main__": websocket.enableTrace(True) if len(sys.argv) < 2: host = "ws://echo.websocket.events/" else: host = sys.argv[1] ws = websocket.WebSocketApp( host, on_message=on_message, on_error=on_error, on_close=on_close ) ws.on_open = on_open ws.run_forever() websocket-client-1.7.0/examples/rel_client.py000066400000000000000000000005401453274240000212710ustar00rootroot00000000000000import rel import websocket addr = "wss://api.gemini.com/v1/marketdata/%s" if __name__ == "__main__": for symbol in ["BTCUSD", "ETHUSD", "ETHBTC"]: ws = websocket.WebSocketApp(addr % (symbol,), on_message=lambda w, m: print(m)) ws.run_forever(dispatcher=rel) rel.signal(2, rel.abort) # Keyboard Interrupt rel.dispatch() websocket-client-1.7.0/mypy.ini000066400000000000000000000002751453274240000164650ustar00rootroot00000000000000[mypy] allow_redefinition=True ignore_missing_imports = True implicit_optional = True warn_return_any = True warn_unused_configs = True files: *.py exclude = (_wsdump.py|test_websocket.py) websocket-client-1.7.0/setup.cfg000066400000000000000000000002601453274240000166010ustar00rootroot00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [flake8] ignore = E231,E241,E501,E722,E741,F401,F403,F405,W503,W504 statistics = True count = True show-source = Truewebsocket-client-1.7.0/setup.py000066400000000000000000000052251453274240000165000ustar00rootroot00000000000000import sys import pkg_resources from setuptools import find_packages, setup """ setup.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ VERSION = "1.7.0" install_requires = [] tests_require = [] setup( name="websocket-client", version=VERSION, description="WebSocket client for Python with low level API options", long_description=open("README.md").read(), long_description_content_type="text/markdown", author="liris", author_email="liris.pp@gmail.com", maintainer="engn33r", maintainer_email="websocket.client@proton.me", license="Apache-2.0", url="https://github.com/websocket-client/websocket-client.git", download_url="https://github.com/websocket-client/websocket-client/releases", python_requires=">=3.8", extras_require={ "test": ["websockets"], "optional": ["python-socks", "wsaccel"], "docs": ["Sphinx >= 6.0", "sphinx_rtd_theme >= 1.1.0"], }, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Topic :: Internet", "Topic :: Software Development :: Libraries :: Python Modules", "Intended Audience :: Developers", ], project_urls={ "Documentation": "https://websocket-client.readthedocs.io/", "Source": "https://github.com/websocket-client/websocket-client/", }, keywords="websockets client", entry_points={ "console_scripts": [ "wsdump=websocket._wsdump:main", ], }, install_requires=install_requires, packages=find_packages(), package_data={"websocket.tests": ["data/*.txt"]}, tests_require=tests_require, test_suite="websocket.tests", ) websocket-client-1.7.0/upload.sh000066400000000000000000000020401453274240000165760ustar00rootroot00000000000000# This is a small script to upload # new releases to PyPI # Create virtual environment python3 -m venv /tmp/ws-venv/ source /tmp/ws-venv/bin/activate # Install dependencies pip3 install -U setuptools wheel twine # build the package python3 setup.py sdist bdist_wheel # Run Twine check to verify descriptions are valid twine check dist/* # Upload to test PyPI first to verify everything # The secure approach is to get an API token # Then pass __token__ as the username and the token value as password # https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives twine upload --repository testpypi dist/* # Now upload to production PyPI # The secure approach is to get an API token # Then pass __token__ as the username and the token value as password # https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives twine upload dist/* # Clean up # Delete the build/, dist/, and websocket_client.egg-info/ directories rm -r build dist websocket_client.egg-info websocket-client-1.7.0/websocket/000077500000000000000000000000001453274240000167505ustar00rootroot00000000000000websocket-client-1.7.0/websocket/__init__.py000066400000000000000000000014411453274240000210610ustar00rootroot00000000000000""" __init__.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from ._abnf import * from ._app import WebSocketApp, setReconnect from ._core import * from ._exceptions import * from ._logging import * from ._socket import * __version__ = "1.7.0" websocket-client-1.7.0/websocket/_abnf.py000066400000000000000000000337751453274240000204060ustar00rootroot00000000000000import array import os import struct import sys from threading import Lock from typing import Callable, Optional, Union from ._exceptions import * from ._utils import validate_utf8 """ _abnf.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ try: # If wsaccel is available, use compiled routines to mask data. # wsaccel only provides around a 10% speed boost compared # to the websocket-client _mask() implementation. # Note that wsaccel is unmaintained. from wsaccel.xormask import XorMaskerSimple def _mask(mask_value: array.array, data_value: array.array) -> bytes: mask_result: bytes = XorMaskerSimple(mask_value).process(data_value) return mask_result except ImportError: # wsaccel is not available, use websocket-client _mask() native_byteorder = sys.byteorder def _mask(mask_value: array.array, data_value: array.array) -> bytes: datalen = len(data_value) int_data_value = int.from_bytes(data_value, native_byteorder) int_mask_value = int.from_bytes( mask_value * (datalen // 4) + mask_value[: datalen % 4], native_byteorder ) return (int_data_value ^ int_mask_value).to_bytes(datalen, native_byteorder) __all__ = [ "ABNF", "continuous_frame", "frame_buffer", "STATUS_NORMAL", "STATUS_GOING_AWAY", "STATUS_PROTOCOL_ERROR", "STATUS_UNSUPPORTED_DATA_TYPE", "STATUS_STATUS_NOT_AVAILABLE", "STATUS_ABNORMAL_CLOSED", "STATUS_INVALID_PAYLOAD", "STATUS_POLICY_VIOLATION", "STATUS_MESSAGE_TOO_BIG", "STATUS_INVALID_EXTENSION", "STATUS_UNEXPECTED_CONDITION", "STATUS_BAD_GATEWAY", "STATUS_TLS_HANDSHAKE_ERROR", ] # closing frame status codes. STATUS_NORMAL = 1000 STATUS_GOING_AWAY = 1001 STATUS_PROTOCOL_ERROR = 1002 STATUS_UNSUPPORTED_DATA_TYPE = 1003 STATUS_STATUS_NOT_AVAILABLE = 1005 STATUS_ABNORMAL_CLOSED = 1006 STATUS_INVALID_PAYLOAD = 1007 STATUS_POLICY_VIOLATION = 1008 STATUS_MESSAGE_TOO_BIG = 1009 STATUS_INVALID_EXTENSION = 1010 STATUS_UNEXPECTED_CONDITION = 1011 STATUS_SERVICE_RESTART = 1012 STATUS_TRY_AGAIN_LATER = 1013 STATUS_BAD_GATEWAY = 1014 STATUS_TLS_HANDSHAKE_ERROR = 1015 VALID_CLOSE_STATUS = ( STATUS_NORMAL, STATUS_GOING_AWAY, STATUS_PROTOCOL_ERROR, STATUS_UNSUPPORTED_DATA_TYPE, STATUS_INVALID_PAYLOAD, STATUS_POLICY_VIOLATION, STATUS_MESSAGE_TOO_BIG, STATUS_INVALID_EXTENSION, STATUS_UNEXPECTED_CONDITION, STATUS_SERVICE_RESTART, STATUS_TRY_AGAIN_LATER, STATUS_BAD_GATEWAY, ) class ABNF: """ ABNF frame class. See http://tools.ietf.org/html/rfc5234 and http://tools.ietf.org/html/rfc6455#section-5.2 """ # operation code values. OPCODE_CONT = 0x0 OPCODE_TEXT = 0x1 OPCODE_BINARY = 0x2 OPCODE_CLOSE = 0x8 OPCODE_PING = 0x9 OPCODE_PONG = 0xA # available operation code value tuple OPCODES = ( OPCODE_CONT, OPCODE_TEXT, OPCODE_BINARY, OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG, ) # opcode human readable string OPCODE_MAP = { OPCODE_CONT: "cont", OPCODE_TEXT: "text", OPCODE_BINARY: "binary", OPCODE_CLOSE: "close", OPCODE_PING: "ping", OPCODE_PONG: "pong", } # data length threshold. LENGTH_7 = 0x7E LENGTH_16 = 1 << 16 LENGTH_63 = 1 << 63 def __init__( self, fin: int = 0, rsv1: int = 0, rsv2: int = 0, rsv3: int = 0, opcode: int = OPCODE_TEXT, mask_value: int = 1, data: Union[str, bytes, None] = "", ) -> None: """ Constructor for ABNF. Please check RFC for arguments. """ self.fin = fin self.rsv1 = rsv1 self.rsv2 = rsv2 self.rsv3 = rsv3 self.opcode = opcode self.mask_value = mask_value if data is None: data = "" self.data = data self.get_mask_key = os.urandom def validate(self, skip_utf8_validation: bool = False) -> None: """ Validate the ABNF frame. Parameters ---------- skip_utf8_validation: skip utf8 validation. """ if self.rsv1 or self.rsv2 or self.rsv3: raise WebSocketProtocolException("rsv is not implemented, yet") if self.opcode not in ABNF.OPCODES: raise WebSocketProtocolException("Invalid opcode %r", self.opcode) if self.opcode == ABNF.OPCODE_PING and not self.fin: raise WebSocketProtocolException("Invalid ping frame.") if self.opcode == ABNF.OPCODE_CLOSE: l = len(self.data) if not l: return if l == 1 or l >= 126: raise WebSocketProtocolException("Invalid close frame.") if l > 2 and not skip_utf8_validation and not validate_utf8(self.data[2:]): raise WebSocketProtocolException("Invalid close frame.") code = 256 * int(self.data[0]) + int(self.data[1]) if not self._is_valid_close_status(code): raise WebSocketProtocolException("Invalid close opcode %r", code) @staticmethod def _is_valid_close_status(code: int) -> bool: return code in VALID_CLOSE_STATUS or (3000 <= code < 5000) def __str__(self) -> str: return f"fin={self.fin} opcode={self.opcode} data={self.data}" @staticmethod def create_frame(data: Union[bytes, str], opcode: int, fin: int = 1) -> "ABNF": """ Create frame to send text, binary and other data. Parameters ---------- data: str data to send. This is string value(byte array). If opcode is OPCODE_TEXT and this value is unicode, data value is converted into unicode string, automatically. opcode: int operation code. please see OPCODE_MAP. fin: int fin flag. if set to 0, create continue fragmentation. """ if opcode == ABNF.OPCODE_TEXT and isinstance(data, str): data = data.encode("utf-8") # mask must be set if send data from client return ABNF(fin, 0, 0, 0, opcode, 1, data) def format(self) -> bytes: """ Format this object to string(byte array) to send data to server. """ if any(x not in (0, 1) for x in [self.fin, self.rsv1, self.rsv2, self.rsv3]): raise ValueError("not 0 or 1") if self.opcode not in ABNF.OPCODES: raise ValueError("Invalid OPCODE") length = len(self.data) if length >= ABNF.LENGTH_63: raise ValueError("data is too long") frame_header = chr( self.fin << 7 | self.rsv1 << 6 | self.rsv2 << 5 | self.rsv3 << 4 | self.opcode ).encode("latin-1") if length < ABNF.LENGTH_7: frame_header += chr(self.mask_value << 7 | length).encode("latin-1") elif length < ABNF.LENGTH_16: frame_header += chr(self.mask_value << 7 | 0x7E).encode("latin-1") frame_header += struct.pack("!H", length) else: frame_header += chr(self.mask_value << 7 | 0x7F).encode("latin-1") frame_header += struct.pack("!Q", length) if not self.mask_value: if isinstance(self.data, str): self.data = self.data.encode("utf-8") return frame_header + self.data mask_key = self.get_mask_key(4) return frame_header + self._get_masked(mask_key) def _get_masked(self, mask_key: Union[str, bytes]) -> bytes: s = ABNF.mask(mask_key, self.data) if isinstance(mask_key, str): mask_key = mask_key.encode("utf-8") return mask_key + s @staticmethod def mask(mask_key: Union[str, bytes], data: Union[str, bytes]) -> bytes: """ Mask or unmask data. Just do xor for each byte Parameters ---------- mask_key: bytes or str 4 byte mask. data: bytes or str data to mask/unmask. """ if data is None: data = "" if isinstance(mask_key, str): mask_key = mask_key.encode("latin-1") if isinstance(data, str): data = data.encode("latin-1") return _mask(array.array("B", mask_key), array.array("B", data)) class frame_buffer: _HEADER_MASK_INDEX = 5 _HEADER_LENGTH_INDEX = 6 def __init__( self, recv_fn: Callable[[int], int], skip_utf8_validation: bool ) -> None: self.recv = recv_fn self.skip_utf8_validation = skip_utf8_validation # Buffers over the packets from the layer beneath until desired amount # bytes of bytes are received. self.recv_buffer: list = [] self.clear() self.lock = Lock() def clear(self) -> None: self.header: Optional[tuple] = None self.length: Optional[int] = None self.mask_value: Union[bytes, str, None] = None def has_received_header(self) -> bool: return self.header is None def recv_header(self) -> None: header = self.recv_strict(2) b1 = header[0] fin = b1 >> 7 & 1 rsv1 = b1 >> 6 & 1 rsv2 = b1 >> 5 & 1 rsv3 = b1 >> 4 & 1 opcode = b1 & 0xF b2 = header[1] has_mask = b2 >> 7 & 1 length_bits = b2 & 0x7F self.header = (fin, rsv1, rsv2, rsv3, opcode, has_mask, length_bits) def has_mask(self) -> Union[bool, int]: if not self.header: return False header_val: int = self.header[frame_buffer._HEADER_MASK_INDEX] return header_val def has_received_length(self) -> bool: return self.length is None def recv_length(self) -> None: bits = self.header[frame_buffer._HEADER_LENGTH_INDEX] length_bits = bits & 0x7F if length_bits == 0x7E: v = self.recv_strict(2) self.length = struct.unpack("!H", v)[0] elif length_bits == 0x7F: v = self.recv_strict(8) self.length = struct.unpack("!Q", v)[0] else: self.length = length_bits def has_received_mask(self) -> bool: return self.mask_value is None def recv_mask(self) -> None: self.mask_value = self.recv_strict(4) if self.has_mask() else "" def recv_frame(self) -> ABNF: with self.lock: # Header if self.has_received_header(): self.recv_header() (fin, rsv1, rsv2, rsv3, opcode, has_mask, _) = self.header # Frame length if self.has_received_length(): self.recv_length() length = self.length # Mask if self.has_received_mask(): self.recv_mask() mask_value = self.mask_value # Payload payload = self.recv_strict(length) if has_mask: payload = ABNF.mask(mask_value, payload) # Reset for next frame self.clear() frame = ABNF(fin, rsv1, rsv2, rsv3, opcode, has_mask, payload) frame.validate(self.skip_utf8_validation) return frame def recv_strict(self, bufsize: int) -> bytes: shortage = bufsize - sum(map(len, self.recv_buffer)) while shortage > 0: # Limit buffer size that we pass to socket.recv() to avoid # fragmenting the heap -- the number of bytes recv() actually # reads is limited by socket buffer and is relatively small, # yet passing large numbers repeatedly causes lots of large # buffers allocated and then shrunk, which results in # fragmentation. bytes_ = self.recv(min(16384, shortage)) self.recv_buffer.append(bytes_) shortage -= len(bytes_) unified = b"".join(self.recv_buffer) if shortage == 0: self.recv_buffer = [] return unified else: self.recv_buffer = [unified[bufsize:]] return unified[:bufsize] class continuous_frame: def __init__(self, fire_cont_frame: bool, skip_utf8_validation: bool) -> None: self.fire_cont_frame = fire_cont_frame self.skip_utf8_validation = skip_utf8_validation self.cont_data: Optional[list] = None self.recving_frames: Optional[int] = None def validate(self, frame: ABNF) -> None: if not self.recving_frames and frame.opcode == ABNF.OPCODE_CONT: raise WebSocketProtocolException("Illegal frame") if self.recving_frames and frame.opcode in ( ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY, ): raise WebSocketProtocolException("Illegal frame") def add(self, frame: ABNF) -> None: if self.cont_data: self.cont_data[1] += frame.data else: if frame.opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): self.recving_frames = frame.opcode self.cont_data = [frame.opcode, frame.data] if frame.fin: self.recving_frames = None def is_fire(self, frame: ABNF) -> Union[bool, int]: return frame.fin or self.fire_cont_frame def extract(self, frame: ABNF) -> tuple: data = self.cont_data self.cont_data = None frame.data = data[1] if ( not self.fire_cont_frame and data[0] == ABNF.OPCODE_TEXT and not self.skip_utf8_validation and not validate_utf8(frame.data) ): raise WebSocketPayloadException(f"cannot decode: {repr(frame.data)}") return data[0], frame websocket-client-1.7.0/websocket/_app.py000066400000000000000000000560761453274240000202570ustar00rootroot00000000000000import inspect import selectors import socket import threading import time from typing import Any, Callable, Optional, Union from . import _logging from ._abnf import ABNF from ._core import WebSocket, getdefaulttimeout from ._exceptions import ( WebSocketConnectionClosedException, WebSocketException, WebSocketTimeoutException, ) from ._url import parse_url """ _app.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["WebSocketApp"] RECONNECT = 0 def setReconnect(reconnectInterval: int) -> None: global RECONNECT RECONNECT = reconnectInterval class DispatcherBase: """ DispatcherBase """ def __init__(self, app: Any, ping_timeout: Union[float, int, None]) -> None: self.app = app self.ping_timeout = ping_timeout def timeout(self, seconds: Union[float, int, None], callback: Callable) -> None: time.sleep(seconds) callback() def reconnect(self, seconds: int, reconnector: Callable) -> None: try: _logging.info( f"reconnect() - retrying in {seconds} seconds [{len(inspect.stack())} frames in stack]" ) time.sleep(seconds) reconnector(reconnecting=True) except KeyboardInterrupt as e: _logging.info(f"User exited {e}") raise e class Dispatcher(DispatcherBase): """ Dispatcher """ def read( self, sock: socket.socket, read_callback: Callable, check_callback: Callable, ) -> None: sel = selectors.DefaultSelector() sel.register(self.app.sock.sock, selectors.EVENT_READ) try: while self.app.keep_running: if sel.select(self.ping_timeout): if not read_callback(): break check_callback() finally: sel.close() class SSLDispatcher(DispatcherBase): """ SSLDispatcher """ def read( self, sock: socket.socket, read_callback: Callable, check_callback: Callable, ) -> None: sock = self.app.sock.sock sel = selectors.DefaultSelector() sel.register(sock, selectors.EVENT_READ) try: while self.app.keep_running: if self.select(sock, sel): if not read_callback(): break check_callback() finally: sel.close() def select(self, sock, sel: selectors.DefaultSelector): sock = self.app.sock.sock if sock.pending(): return [ sock, ] r = sel.select(self.ping_timeout) if len(r) > 0: return r[0][0] class WrappedDispatcher: """ WrappedDispatcher """ def __init__(self, app, ping_timeout: Union[float, int, None], dispatcher) -> None: self.app = app self.ping_timeout = ping_timeout self.dispatcher = dispatcher dispatcher.signal(2, dispatcher.abort) # keyboard interrupt def read( self, sock: socket.socket, read_callback: Callable, check_callback: Callable, ) -> None: self.dispatcher.read(sock, read_callback) self.ping_timeout and self.timeout(self.ping_timeout, check_callback) def timeout(self, seconds: float, callback: Callable) -> None: self.dispatcher.timeout(seconds, callback) def reconnect(self, seconds: int, reconnector: Callable) -> None: self.timeout(seconds, reconnector) class WebSocketApp: """ Higher level of APIs are provided. The interface is like JavaScript WebSocket object. """ def __init__( self, url: str, header: Union[list, dict, Callable, None] = None, on_open: Optional[Callable[[WebSocket], None]] = None, on_message: Optional[Callable[[WebSocket, Any], None]] = None, on_error: Optional[Callable[[WebSocket, Any], None]] = None, on_close: Optional[Callable[[WebSocket, Any, Any], None]] = None, on_ping: Optional[Callable] = None, on_pong: Optional[Callable] = None, on_cont_message: Optional[Callable] = None, keep_running: bool = True, get_mask_key: Optional[Callable] = None, cookie: Optional[str] = None, subprotocols: Optional[list] = None, on_data: Optional[Callable] = None, socket: Optional[socket.socket] = None, ) -> None: """ WebSocketApp initialization Parameters ---------- url: str Websocket url. header: list or dict or Callable Custom header for websocket handshake. If the parameter is a callable object, it is called just before the connection attempt. The returned dict or list is used as custom header value. This could be useful in order to properly setup timestamp dependent headers. on_open: function Callback object which is called at opening websocket. on_open has one argument. The 1st argument is this class object. on_message: function Callback object which is called when received data. on_message has 2 arguments. The 1st argument is this class object. The 2nd argument is utf-8 data received from the server. on_error: function Callback object which is called when we get error. on_error has 2 arguments. The 1st argument is this class object. The 2nd argument is exception object. on_close: function Callback object which is called when connection is closed. on_close has 3 arguments. The 1st argument is this class object. The 2nd argument is close_status_code. The 3rd argument is close_msg. on_cont_message: function Callback object which is called when a continuation frame is received. on_cont_message has 3 arguments. The 1st argument is this class object. The 2nd argument is utf-8 string which we get from the server. The 3rd argument is continue flag. if 0, the data continue to next frame data on_data: function Callback object which is called when a message received. This is called before on_message or on_cont_message, and then on_message or on_cont_message is called. on_data has 4 argument. The 1st argument is this class object. The 2nd argument is utf-8 string which we get from the server. The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came. The 4th argument is continue flag. If 0, the data continue keep_running: bool This parameter is obsolete and ignored. get_mask_key: function A callable function to get new mask keys, see the WebSocket.set_mask_key's docstring for more information. cookie: str Cookie value. subprotocols: list List of available sub protocols. Default is None. socket: socket Pre-initialized stream socket. """ self.url = url self.header = header if header is not None else [] self.cookie = cookie self.on_open = on_open self.on_message = on_message self.on_data = on_data self.on_error = on_error self.on_close = on_close self.on_ping = on_ping self.on_pong = on_pong self.on_cont_message = on_cont_message self.keep_running = False self.get_mask_key = get_mask_key self.sock: Optional[WebSocket] = None self.last_ping_tm = float(0) self.last_pong_tm = float(0) self.ping_thread: Optional[threading.Thread] = None self.stop_ping: Optional[threading.Event] = None self.ping_interval = float(0) self.ping_timeout: Union[float, int, None] = None self.ping_payload = "" self.subprotocols = subprotocols self.prepared_socket = socket self.has_errored = False self.has_done_teardown = False self.has_done_teardown_lock = threading.Lock() def send(self, data: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> None: """ send message Parameters ---------- data: str Message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: int Operation code of data. Default is OPCODE_TEXT. """ if not self.sock or self.sock.send(data, opcode) == 0: raise WebSocketConnectionClosedException("Connection is already closed.") def send_text(self, text_data: str) -> None: """ Sends UTF-8 encoded text. """ if not self.sock or self.sock.send(text_data, ABNF.OPCODE_TEXT) == 0: raise WebSocketConnectionClosedException("Connection is already closed.") def send_bytes(self, data: Union[bytes, bytearray]) -> None: """ Sends a sequence of bytes. """ if not self.sock or self.sock.send(data, ABNF.OPCODE_BINARY) == 0: raise WebSocketConnectionClosedException("Connection is already closed.") def close(self, **kwargs) -> None: """ Close websocket connection. """ self.keep_running = False if self.sock: self.sock.close(**kwargs) self.sock = None def _start_ping_thread(self) -> None: self.last_ping_tm = self.last_pong_tm = float(0) self.stop_ping = threading.Event() self.ping_thread = threading.Thread(target=self._send_ping) self.ping_thread.daemon = True self.ping_thread.start() def _stop_ping_thread(self) -> None: if self.stop_ping: self.stop_ping.set() if self.ping_thread and self.ping_thread.is_alive(): self.ping_thread.join(3) self.last_ping_tm = self.last_pong_tm = float(0) def _send_ping(self) -> None: if self.stop_ping.wait(self.ping_interval) or self.keep_running is False: return while not self.stop_ping.wait(self.ping_interval) and self.keep_running is True: if self.sock: self.last_ping_tm = time.time() try: _logging.debug("Sending ping") self.sock.ping(self.ping_payload) except Exception as e: _logging.debug(f"Failed to send ping: {e}") def run_forever( self, sockopt: tuple = None, sslopt: dict = None, ping_interval: Union[float, int] = 0, ping_timeout: Union[float, int, None] = None, ping_payload: str = "", http_proxy_host: str = None, http_proxy_port: Union[int, str] = None, http_no_proxy: list = None, http_proxy_auth: tuple = None, http_proxy_timeout: Optional[float] = None, skip_utf8_validation: bool = False, host: str = None, origin: str = None, dispatcher=None, suppress_origin: bool = False, proxy_type: str = None, reconnect: int = None, ) -> bool: """ Run event loop for WebSocket framework. This loop is an infinite loop and is alive while websocket is available. Parameters ---------- sockopt: tuple Values for socket.setsockopt. sockopt must be tuple and each element is argument of sock.setsockopt. sslopt: dict Optional dict object for ssl socket option. ping_interval: int or float Automatically send "ping" command every specified period (in seconds). If set to 0, no ping is sent periodically. ping_timeout: int or float Timeout (in seconds) if the pong message is not received. ping_payload: str Payload message to send with each ping. http_proxy_host: str HTTP proxy host name. http_proxy_port: int or str HTTP proxy port. If not set, set to 80. http_no_proxy: list Whitelisted host names that don't use the proxy. http_proxy_timeout: int or float HTTP proxy timeout, default is 60 sec as per python-socks. http_proxy_auth: tuple HTTP proxy auth information. tuple of username and password. Default is None. skip_utf8_validation: bool skip utf8 validation. host: str update host header. origin: str update origin header. dispatcher: Dispatcher object customize reading data from socket. suppress_origin: bool suppress outputting origin header. proxy_type: str type of proxy from: http, socks4, socks4a, socks5, socks5h reconnect: int delay interval when reconnecting Returns ------- teardown: bool False if the `WebSocketApp` is closed or caught KeyboardInterrupt, True if any other exception was raised during a loop. """ if reconnect is None: reconnect = RECONNECT if ping_timeout is not None and ping_timeout <= 0: raise WebSocketException("Ensure ping_timeout > 0") if ping_interval is not None and ping_interval < 0: raise WebSocketException("Ensure ping_interval >= 0") if ping_timeout and ping_interval and ping_interval <= ping_timeout: raise WebSocketException("Ensure ping_interval > ping_timeout") if not sockopt: sockopt = () if not sslopt: sslopt = {} if self.sock: raise WebSocketException("socket is already opened") self.ping_interval = ping_interval self.ping_timeout = ping_timeout self.ping_payload = ping_payload self.keep_running = True def teardown(close_frame: ABNF = None): """ Tears down the connection. Parameters ---------- close_frame: ABNF frame If close_frame is set, the on_close handler is invoked with the statusCode and reason from the provided frame. """ # teardown() is called in many code paths to ensure resources are cleaned up and on_close is fired. # To ensure the work is only done once, we use this bool and lock. with self.has_done_teardown_lock: if self.has_done_teardown: return self.has_done_teardown = True self._stop_ping_thread() self.keep_running = False if self.sock: self.sock.close() close_status_code, close_reason = self._get_close_args( close_frame if close_frame else None ) self.sock = None # Finally call the callback AFTER all teardown is complete self._callback(self.on_close, close_status_code, close_reason) def setSock(reconnecting: bool = False) -> None: if reconnecting and self.sock: self.sock.shutdown() self.sock = WebSocket( self.get_mask_key, sockopt=sockopt, sslopt=sslopt, fire_cont_frame=self.on_cont_message is not None, skip_utf8_validation=skip_utf8_validation, enable_multithread=True, ) self.sock.settimeout(getdefaulttimeout()) try: header = self.header() if callable(self.header) else self.header self.sock.connect( self.url, header=header, cookie=self.cookie, http_proxy_host=http_proxy_host, http_proxy_port=http_proxy_port, http_no_proxy=http_no_proxy, http_proxy_auth=http_proxy_auth, http_proxy_timeout=http_proxy_timeout, subprotocols=self.subprotocols, host=host, origin=origin, suppress_origin=suppress_origin, proxy_type=proxy_type, socket=self.prepared_socket, ) _logging.info("Websocket connected") if self.ping_interval: self._start_ping_thread() self._callback(self.on_open) dispatcher.read(self.sock.sock, read, check) except ( WebSocketConnectionClosedException, ConnectionRefusedError, KeyboardInterrupt, SystemExit, Exception, ) as e: handleDisconnect(e, reconnecting) def read() -> bool: if not self.keep_running: return teardown() try: op_code, frame = self.sock.recv_data_frame(True) except ( WebSocketConnectionClosedException, KeyboardInterrupt, ) as e: if custom_dispatcher: return handleDisconnect(e) else: raise e if op_code == ABNF.OPCODE_CLOSE: return teardown(frame) elif op_code == ABNF.OPCODE_PING: self._callback(self.on_ping, frame.data) elif op_code == ABNF.OPCODE_PONG: self.last_pong_tm = time.time() self._callback(self.on_pong, frame.data) elif op_code == ABNF.OPCODE_CONT and self.on_cont_message: self._callback(self.on_data, frame.data, frame.opcode, frame.fin) self._callback(self.on_cont_message, frame.data, frame.fin) else: data = frame.data if op_code == ABNF.OPCODE_TEXT and not skip_utf8_validation: data = data.decode("utf-8") self._callback(self.on_data, data, frame.opcode, True) self._callback(self.on_message, data) return True def check() -> bool: if self.ping_timeout: has_timeout_expired = ( time.time() - self.last_ping_tm > self.ping_timeout ) has_pong_not_arrived_after_last_ping = ( self.last_pong_tm - self.last_ping_tm < 0 ) has_pong_arrived_too_late = ( self.last_pong_tm - self.last_ping_tm > self.ping_timeout ) if ( self.last_ping_tm and has_timeout_expired and ( has_pong_not_arrived_after_last_ping or has_pong_arrived_too_late ) ): raise WebSocketTimeoutException("ping/pong timed out") return True def handleDisconnect( e: Union[ WebSocketConnectionClosedException, ConnectionRefusedError, KeyboardInterrupt, SystemExit, Exception, ], reconnecting: bool = False, ) -> bool: self.has_errored = True self._stop_ping_thread() if not reconnecting: self._callback(self.on_error, e) if isinstance(e, (KeyboardInterrupt, SystemExit)): teardown() # Propagate further raise if reconnect: _logging.info(f"{e} - reconnect") if custom_dispatcher: _logging.debug( f"Calling custom dispatcher reconnect [{len(inspect.stack())} frames in stack]" ) dispatcher.reconnect(reconnect, setSock) else: _logging.error(f"{e} - goodbye") teardown() custom_dispatcher = bool(dispatcher) dispatcher = self.create_dispatcher( ping_timeout, dispatcher, parse_url(self.url)[3] ) try: setSock() if not custom_dispatcher and reconnect: while self.keep_running: _logging.debug( f"Calling dispatcher reconnect [{len(inspect.stack())} frames in stack]" ) dispatcher.reconnect(reconnect, setSock) except (KeyboardInterrupt, Exception) as e: _logging.info(f"tearing down on exception {e}") teardown() finally: if not custom_dispatcher: # Ensure teardown was called before returning from run_forever teardown() return self.has_errored def create_dispatcher( self, ping_timeout: Union[float, int, None], dispatcher: Optional[DispatcherBase] = None, is_ssl: bool = False, ) -> Union[Dispatcher, SSLDispatcher, WrappedDispatcher]: if dispatcher: # If custom dispatcher is set, use WrappedDispatcher return WrappedDispatcher(self, ping_timeout, dispatcher) timeout = ping_timeout or 10 if is_ssl: return SSLDispatcher(self, timeout) return Dispatcher(self, timeout) def _get_close_args(self, close_frame: ABNF) -> list: """ _get_close_args extracts the close code and reason from the close body if it exists (RFC6455 says WebSocket Connection Close Code is optional) """ # Need to catch the case where close_frame is None # Otherwise the following if statement causes an error if not self.on_close or not close_frame: return [None, None] # Extract close frame status code if close_frame.data and len(close_frame.data) >= 2: close_status_code = 256 * int(close_frame.data[0]) + int( close_frame.data[1] ) reason = close_frame.data[2:] if isinstance(reason, bytes): reason = reason.decode("utf-8") return [close_status_code, reason] else: # Most likely reached this because len(close_frame_data.data) < 2 return [None, None] def _callback(self, callback, *args) -> None: if callback: try: callback(self, *args) except Exception as e: _logging.error(f"error from callback {callback}: {e}") if self.on_error: self.on_error(self, e) websocket-client-1.7.0/websocket/_cookiejar.py000066400000000000000000000045621453274240000214360ustar00rootroot00000000000000import http.cookies from typing import Optional """ _cookiejar.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class SimpleCookieJar: def __init__(self) -> None: self.jar: dict = dict() def add(self, set_cookie: Optional[str]) -> None: if set_cookie: simpleCookie = http.cookies.SimpleCookie(set_cookie) for k, v in simpleCookie.items(): if domain := v.get("domain"): if not domain.startswith("."): domain = f".{domain}" cookie = ( self.jar.get(domain) if self.jar.get(domain) else http.cookies.SimpleCookie() ) cookie.update(simpleCookie) self.jar[domain.lower()] = cookie def set(self, set_cookie: str) -> None: if set_cookie: simpleCookie = http.cookies.SimpleCookie(set_cookie) for k, v in simpleCookie.items(): if domain := v.get("domain"): if not domain.startswith("."): domain = f".{domain}" self.jar[domain.lower()] = simpleCookie def get(self, host: str) -> str: if not host: return "" cookies = [] for domain, simpleCookie in self.jar.items(): host = host.lower() if host.endswith(domain) or host == domain[1:]: cookies.append(self.jar.get(domain)) return "; ".join( filter( None, sorted( [ "%s=%s" % (k, v.value) for cookie in filter(None, cookies) for k, v in cookie.items() ] ), ) ) websocket-client-1.7.0/websocket/_core.py000066400000000000000000000505231453274240000204160ustar00rootroot00000000000000import socket import struct import threading import time from typing import Optional, Union # websocket modules from ._abnf import * from ._exceptions import * from ._handshake import * from ._http import * from ._logging import * from ._socket import * from ._ssl_compat import * from ._utils import * """ _core.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["WebSocket", "create_connection"] class WebSocket: """ Low level WebSocket interface. This class is based on the WebSocket protocol `draft-hixie-thewebsocketprotocol-76 `_ We can connect to the websocket server and send/receive data. The following example is an echo client. >>> import websocket >>> ws = websocket.WebSocket() >>> ws.connect("ws://echo.websocket.events") >>> ws.recv() 'echo.websocket.events sponsored by Lob.com' >>> ws.send("Hello, Server") 19 >>> ws.recv() 'Hello, Server' >>> ws.close() Parameters ---------- get_mask_key: func A callable function to get new mask keys, see the WebSocket.set_mask_key's docstring for more information. sockopt: tuple Values for socket.setsockopt. sockopt must be tuple and each element is argument of sock.setsockopt. sslopt: dict Optional dict object for ssl socket options. See FAQ for details. fire_cont_frame: bool Fire recv event for each cont frame. Default is False. enable_multithread: bool If set to True, lock send method. skip_utf8_validation: bool Skip utf8 validation. """ def __init__( self, get_mask_key=None, sockopt=None, sslopt=None, fire_cont_frame: bool = False, enable_multithread: bool = True, skip_utf8_validation: bool = False, **_, ): """ Initialize WebSocket object. Parameters ---------- sslopt: dict Optional dict object for ssl socket options. See FAQ for details. """ self.sock_opt = sock_opt(sockopt, sslopt) self.handshake_response = None self.sock: Optional[socket.socket] = None self.connected = False self.get_mask_key = get_mask_key # These buffer over the build-up of a single frame. self.frame_buffer = frame_buffer(self._recv, skip_utf8_validation) self.cont_frame = continuous_frame(fire_cont_frame, skip_utf8_validation) if enable_multithread: self.lock = threading.Lock() self.readlock = threading.Lock() else: self.lock = NoLock() self.readlock = NoLock() def __iter__(self): """ Allow iteration over websocket, implying sequential `recv` executions. """ while True: yield self.recv() def __next__(self): return self.recv() def next(self): return self.__next__() def fileno(self): return self.sock.fileno() def set_mask_key(self, func): """ Set function to create mask key. You can customize mask key generator. Mainly, this is for testing purpose. Parameters ---------- func: func callable object. the func takes 1 argument as integer. The argument means length of mask key. This func must return string(byte array), which length is argument specified. """ self.get_mask_key = func def gettimeout(self) -> Union[float, int, None]: """ Get the websocket timeout (in seconds) as an int or float Returns ---------- timeout: int or float returns timeout value (in seconds). This value could be either float/integer. """ return self.sock_opt.timeout def settimeout(self, timeout: Union[float, int, None]): """ Set the timeout to the websocket. Parameters ---------- timeout: int or float timeout time (in seconds). This value could be either float/integer. """ self.sock_opt.timeout = timeout if self.sock: self.sock.settimeout(timeout) timeout = property(gettimeout, settimeout) def getsubprotocol(self): """ Get subprotocol """ if self.handshake_response: return self.handshake_response.subprotocol else: return None subprotocol = property(getsubprotocol) def getstatus(self): """ Get handshake status """ if self.handshake_response: return self.handshake_response.status else: return None status = property(getstatus) def getheaders(self): """ Get handshake response header """ if self.handshake_response: return self.handshake_response.headers else: return None def is_ssl(self): try: return isinstance(self.sock, ssl.SSLSocket) except: return False headers = property(getheaders) def connect(self, url, **options): """ Connect to url. url is websocket url scheme. ie. ws://host:port/resource You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> ws = WebSocket() >>> ws.connect("ws://echo.websocket.events", ... header=["User-Agent: MyProgram", ... "x-custom: header"]) Parameters ---------- header: list or dict Custom http header list or dict. cookie: str Cookie value. origin: str Custom origin url. connection: str Custom connection header value. Default value "Upgrade" set in _handshake.py suppress_origin: bool Suppress outputting origin header. host: str Custom host header string. timeout: int or float Socket timeout time. This value is an integer or float. If you set None for this value, it means "use default_timeout value" http_proxy_host: str HTTP proxy host name. http_proxy_port: str or int HTTP proxy port. Default is 80. http_no_proxy: list Whitelisted host names that don't use the proxy. http_proxy_auth: tuple HTTP proxy auth information. Tuple of username and password. Default is None. http_proxy_timeout: int or float HTTP proxy timeout, default is 60 sec as per python-socks. redirect_limit: int Number of redirects to follow. subprotocols: list List of available subprotocols. Default is None. socket: socket Pre-initialized stream socket. """ self.sock_opt.timeout = options.get("timeout", self.sock_opt.timeout) self.sock, addrs = connect( url, self.sock_opt, proxy_info(**options), options.pop("socket", None) ) try: self.handshake_response = handshake(self.sock, url, *addrs, **options) for attempt in range(options.pop("redirect_limit", 3)): if self.handshake_response.status in SUPPORTED_REDIRECT_STATUSES: url = self.handshake_response.headers["location"] self.sock.close() self.sock, addrs = connect( url, self.sock_opt, proxy_info(**options), options.pop("socket", None), ) self.handshake_response = handshake( self.sock, url, *addrs, **options ) self.connected = True except: if self.sock: self.sock.close() self.sock = None raise def send(self, payload: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> int: """ Send the data as string. Parameters ---------- payload: str Payload must be utf-8 string or unicode, If the opcode is OPCODE_TEXT. Otherwise, it must be string(byte array). opcode: int Operation code (opcode) to send. """ frame = ABNF.create_frame(payload, opcode) return self.send_frame(frame) def send_text(self, text_data: str) -> int: """ Sends UTF-8 encoded text. """ return self.send(text_data, ABNF.OPCODE_TEXT) def send_bytes(self, data: Union[bytes, bytearray]) -> int: """ Sends a sequence of bytes. """ return self.send(data, ABNF.OPCODE_BINARY) def send_frame(self, frame) -> int: """ Send the data frame. >>> ws = create_connection("ws://echo.websocket.events") >>> frame = ABNF.create_frame("Hello", ABNF.OPCODE_TEXT) >>> ws.send_frame(frame) >>> cont_frame = ABNF.create_frame("My name is ", ABNF.OPCODE_CONT, 0) >>> ws.send_frame(frame) >>> cont_frame = ABNF.create_frame("Foo Bar", ABNF.OPCODE_CONT, 1) >>> ws.send_frame(frame) Parameters ---------- frame: ABNF frame frame data created by ABNF.create_frame """ if self.get_mask_key: frame.get_mask_key = self.get_mask_key data = frame.format() length = len(data) if isEnabledForTrace(): trace(f"++Sent raw: {repr(data)}") trace(f"++Sent decoded: {frame.__str__()}") with self.lock: while data: l = self._send(data) data = data[l:] return length def send_binary(self, payload: bytes) -> int: """ Send a binary message (OPCODE_BINARY). Parameters ---------- payload: bytes payload of message to send. """ return self.send(payload, ABNF.OPCODE_BINARY) def ping(self, payload: Union[str, bytes] = ""): """ Send ping data. Parameters ---------- payload: str data payload to send server. """ if isinstance(payload, str): payload = payload.encode("utf-8") self.send(payload, ABNF.OPCODE_PING) def pong(self, payload: Union[str, bytes] = ""): """ Send pong data. Parameters ---------- payload: str data payload to send server. """ if isinstance(payload, str): payload = payload.encode("utf-8") self.send(payload, ABNF.OPCODE_PONG) def recv(self) -> Union[str, bytes]: """ Receive string data(byte array) from the server. Returns ---------- data: string (byte array) value. """ with self.readlock: opcode, data = self.recv_data() if opcode == ABNF.OPCODE_TEXT: data_received: Union[bytes, str] = data if isinstance(data_received, bytes): return data_received.decode("utf-8") elif isinstance(data_received, str): return data_received elif opcode == ABNF.OPCODE_BINARY: data_binary: bytes = data return data_binary else: return "" def recv_data(self, control_frame: bool = False) -> tuple: """ Receive data with operation code. Parameters ---------- control_frame: bool a boolean flag indicating whether to return control frame data, defaults to False Returns ------- opcode, frame.data: tuple tuple of operation code and string(byte array) value. """ opcode, frame = self.recv_data_frame(control_frame) return opcode, frame.data def recv_data_frame(self, control_frame: bool = False) -> tuple: """ Receive data with operation code. If a valid ping message is received, a pong response is sent. Parameters ---------- control_frame: bool a boolean flag indicating whether to return control frame data, defaults to False Returns ------- frame.opcode, frame: tuple tuple of operation code and string(byte array) value. """ while True: frame = self.recv_frame() if isEnabledForTrace(): trace(f"++Rcv raw: {repr(frame.format())}") trace(f"++Rcv decoded: {frame.__str__()}") if not frame: # handle error: # 'NoneType' object has no attribute 'opcode' raise WebSocketProtocolException(f"Not a valid frame {frame}") elif frame.opcode in ( ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY, ABNF.OPCODE_CONT, ): self.cont_frame.validate(frame) self.cont_frame.add(frame) if self.cont_frame.is_fire(frame): return self.cont_frame.extract(frame) elif frame.opcode == ABNF.OPCODE_CLOSE: self.send_close() return frame.opcode, frame elif frame.opcode == ABNF.OPCODE_PING: if len(frame.data) < 126: self.pong(frame.data) else: raise WebSocketProtocolException("Ping message is too long") if control_frame: return frame.opcode, frame elif frame.opcode == ABNF.OPCODE_PONG: if control_frame: return frame.opcode, frame def recv_frame(self): """ Receive data as frame from server. Returns ------- self.frame_buffer.recv_frame(): ABNF frame object """ return self.frame_buffer.recv_frame() def send_close(self, status: int = STATUS_NORMAL, reason: bytes = b""): """ Send close data to the server. Parameters ---------- status: int Status code to send. See STATUS_XXX. reason: str or bytes The reason to close. This must be string or UTF-8 bytes. """ if status < 0 or status >= ABNF.LENGTH_16: raise ValueError("code is invalid range") self.connected = False self.send(struct.pack("!H", status) + reason, ABNF.OPCODE_CLOSE) def close(self, status: int = STATUS_NORMAL, reason: bytes = b"", timeout: int = 3): """ Close Websocket object Parameters ---------- status: int Status code to send. See VALID_CLOSE_STATUS in ABNF. reason: bytes The reason to close in UTF-8. timeout: int or float Timeout until receive a close frame. If None, it will wait forever until receive a close frame. """ if not self.connected: return if status < 0 or status >= ABNF.LENGTH_16: raise ValueError("code is invalid range") try: self.connected = False self.send(struct.pack("!H", status) + reason, ABNF.OPCODE_CLOSE) sock_timeout = self.sock.gettimeout() self.sock.settimeout(timeout) start_time = time.time() while timeout is None or time.time() - start_time < timeout: try: frame = self.recv_frame() if frame.opcode != ABNF.OPCODE_CLOSE: continue if isEnabledForError(): recv_status = struct.unpack("!H", frame.data[0:2])[0] if recv_status >= 3000 and recv_status <= 4999: debug(f"close status: {repr(recv_status)}") elif recv_status != STATUS_NORMAL: error(f"close status: {repr(recv_status)}") break except: break self.sock.settimeout(sock_timeout) self.sock.shutdown(socket.SHUT_RDWR) except: pass self.shutdown() def abort(self): """ Low-level asynchronous abort, wakes up other threads that are waiting in recv_* """ if self.connected: self.sock.shutdown(socket.SHUT_RDWR) def shutdown(self): """ close socket, immediately. """ if self.sock: self.sock.close() self.sock = None self.connected = False def _send(self, data: Union[str, bytes]): return send(self.sock, data) def _recv(self, bufsize): try: return recv(self.sock, bufsize) except WebSocketConnectionClosedException: if self.sock: self.sock.close() self.sock = None self.connected = False raise def create_connection(url: str, timeout=None, class_=WebSocket, **options): """ Connect to url and return websocket object. Connect to url and return the WebSocket object. Passing optional timeout parameter will set the timeout on the socket. If no timeout is supplied, the global default timeout setting returned by getdefaulttimeout() is used. You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> conn = create_connection("ws://echo.websocket.events", ... header=["User-Agent: MyProgram", ... "x-custom: header"]) Parameters ---------- class_: class class to instantiate when creating the connection. It has to implement settimeout and connect. It's __init__ should be compatible with WebSocket.__init__, i.e. accept all of it's kwargs. header: list or dict custom http header list or dict. cookie: str Cookie value. origin: str custom origin url. suppress_origin: bool suppress outputting origin header. host: str custom host header string. timeout: int or float socket timeout time. This value could be either float/integer. If set to None, it uses the default_timeout value. http_proxy_host: str HTTP proxy host name. http_proxy_port: str or int HTTP proxy port. If not set, set to 80. http_no_proxy: list Whitelisted host names that don't use the proxy. http_proxy_auth: tuple HTTP proxy auth information. tuple of username and password. Default is None. http_proxy_timeout: int or float HTTP proxy timeout, default is 60 sec as per python-socks. enable_multithread: bool Enable lock for multithread. redirect_limit: int Number of redirects to follow. sockopt: tuple Values for socket.setsockopt. sockopt must be a tuple and each element is an argument of sock.setsockopt. sslopt: dict Optional dict object for ssl socket options. See FAQ for details. subprotocols: list List of available subprotocols. Default is None. skip_utf8_validation: bool Skip utf8 validation. socket: socket Pre-initialized stream socket. """ sockopt = options.pop("sockopt", []) sslopt = options.pop("sslopt", {}) fire_cont_frame = options.pop("fire_cont_frame", False) enable_multithread = options.pop("enable_multithread", True) skip_utf8_validation = options.pop("skip_utf8_validation", False) websock = class_( sockopt=sockopt, sslopt=sslopt, fire_cont_frame=fire_cont_frame, enable_multithread=enable_multithread, skip_utf8_validation=skip_utf8_validation, **options, ) websock.settimeout(timeout if timeout is not None else getdefaulttimeout()) websock.connect(url, **options) return websock websocket-client-1.7.0/websocket/_exceptions.py000066400000000000000000000042021453274240000216400ustar00rootroot00000000000000""" _exceptions.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class WebSocketException(Exception): """ WebSocket exception class. """ pass class WebSocketProtocolException(WebSocketException): """ If the WebSocket protocol is invalid, this exception will be raised. """ pass class WebSocketPayloadException(WebSocketException): """ If the WebSocket payload is invalid, this exception will be raised. """ pass class WebSocketConnectionClosedException(WebSocketException): """ If remote host closed the connection or some network error happened, this exception will be raised. """ pass class WebSocketTimeoutException(WebSocketException): """ WebSocketTimeoutException will be raised at socket timeout during read/write data. """ pass class WebSocketProxyException(WebSocketException): """ WebSocketProxyException will be raised when proxy error occurred. """ pass class WebSocketBadStatusException(WebSocketException): """ WebSocketBadStatusException will be raised when we get bad handshake status code. """ def __init__( self, message: str, status_code: int, status_message=None, resp_headers=None, resp_body=None, ): super().__init__(message) self.status_code = status_code self.resp_headers = resp_headers self.resp_body = resp_body class WebSocketAddressException(WebSocketException): """ If the websocket address info cannot be found, this exception will be raised. """ pass websocket-client-1.7.0/websocket/_handshake.py000066400000000000000000000145541453274240000214200ustar00rootroot00000000000000""" _handshake.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import hashlib import hmac import os from base64 import encodebytes as base64encode from http import HTTPStatus from ._cookiejar import SimpleCookieJar from ._exceptions import * from ._http import * from ._logging import * from ._socket import * __all__ = ["handshake_response", "handshake", "SUPPORTED_REDIRECT_STATUSES"] # websocket supported version. VERSION = 13 SUPPORTED_REDIRECT_STATUSES = ( HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.FOUND, HTTPStatus.SEE_OTHER, HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ) SUCCESS_STATUSES = SUPPORTED_REDIRECT_STATUSES + (HTTPStatus.SWITCHING_PROTOCOLS,) CookieJar = SimpleCookieJar() class handshake_response: def __init__(self, status: int, headers: dict, subprotocol): self.status = status self.headers = headers self.subprotocol = subprotocol CookieJar.add(headers.get("set-cookie")) def handshake( sock, url: str, hostname: str, port: int, resource: str, **options ) -> handshake_response: headers, key = _get_handshake_headers(resource, url, hostname, port, options) header_str = "\r\n".join(headers) send(sock, header_str) dump("request header", header_str) status, resp = _get_resp_headers(sock) if status in SUPPORTED_REDIRECT_STATUSES: return handshake_response(status, resp, None) success, subproto = _validate(resp, key, options.get("subprotocols")) if not success: raise WebSocketException("Invalid WebSocket Header") return handshake_response(status, resp, subproto) def _pack_hostname(hostname: str) -> str: # IPv6 address if ":" in hostname: return f"[{hostname}]" return hostname def _get_handshake_headers( resource: str, url: str, host: str, port: int, options: dict ) -> tuple: headers = [f"GET {resource} HTTP/1.1", "Upgrade: websocket"] if port in [80, 443]: hostport = _pack_hostname(host) else: hostport = f"{_pack_hostname(host)}:{port}" if options.get("host"): headers.append(f'Host: {options["host"]}') else: headers.append(f"Host: {hostport}") # scheme indicates whether http or https is used in Origin # The same approach is used in parse_url of _url.py to set default port scheme, url = url.split(":", 1) if not options.get("suppress_origin"): if "origin" in options and options["origin"] is not None: headers.append(f'Origin: {options["origin"]}') elif scheme == "wss": headers.append(f"Origin: https://{hostport}") else: headers.append(f"Origin: http://{hostport}") key = _create_sec_websocket_key() # Append Sec-WebSocket-Key & Sec-WebSocket-Version if not manually specified if not options.get("header") or "Sec-WebSocket-Key" not in options["header"]: headers.append(f"Sec-WebSocket-Key: {key}") else: key = options["header"]["Sec-WebSocket-Key"] if not options.get("header") or "Sec-WebSocket-Version" not in options["header"]: headers.append(f"Sec-WebSocket-Version: {VERSION}") if not options.get("connection"): headers.append("Connection: Upgrade") else: headers.append(options["connection"]) if subprotocols := options.get("subprotocols"): headers.append(f'Sec-WebSocket-Protocol: {",".join(subprotocols)}') if header := options.get("header"): if isinstance(header, dict): header = [": ".join([k, v]) for k, v in header.items() if v is not None] headers.extend(header) server_cookie = CookieJar.get(host) client_cookie = options.get("cookie", None) if cookie := "; ".join(filter(None, [server_cookie, client_cookie])): headers.append(f"Cookie: {cookie}") headers.extend(("", "")) return headers, key def _get_resp_headers(sock, success_statuses: tuple = SUCCESS_STATUSES) -> tuple: status, resp_headers, status_message = read_headers(sock) if status not in success_statuses: content_len = resp_headers.get("content-length") if content_len: response_body = sock.recv( int(content_len) ) # read the body of the HTTP error message response and include it in the exception else: response_body = None raise WebSocketBadStatusException( f"Handshake status {status} {status_message} -+-+- {resp_headers} -+-+- {response_body}", status, status_message, resp_headers, response_body, ) return status, resp_headers _HEADERS_TO_CHECK = { "upgrade": "websocket", "connection": "upgrade", } def _validate(headers, key: str, subprotocols) -> tuple: subproto = None for k, v in _HEADERS_TO_CHECK.items(): r = headers.get(k, None) if not r: return False, None r = [x.strip().lower() for x in r.split(",")] if v not in r: return False, None if subprotocols: subproto = headers.get("sec-websocket-protocol", None) if not subproto or subproto.lower() not in [s.lower() for s in subprotocols]: error(f"Invalid subprotocol: {subprotocols}") return False, None subproto = subproto.lower() result = headers.get("sec-websocket-accept", None) if not result: return False, None result = result.lower() if isinstance(result, str): result = result.encode("utf-8") value = f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("utf-8") hashed = base64encode(hashlib.sha1(value).digest()).strip().lower() if hmac.compare_digest(hashed, result): return True, subproto else: return False, None def _create_sec_websocket_key() -> str: randomness = os.urandom(16) return base64encode(randomness).decode("utf-8").strip() websocket-client-1.7.0/websocket/_http.py000066400000000000000000000305641453274240000204500ustar00rootroot00000000000000""" _http.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import errno import os import socket from base64 import encodebytes as base64encode from ._exceptions import * from ._logging import * from ._socket import * from ._ssl_compat import * from ._url import * __all__ = ["proxy_info", "connect", "read_headers"] try: from python_socks._errors import * from python_socks._types import ProxyType from python_socks.sync import Proxy HAVE_PYTHON_SOCKS = True except: HAVE_PYTHON_SOCKS = False class ProxyError(Exception): pass class ProxyTimeoutError(Exception): pass class ProxyConnectionError(Exception): pass class proxy_info: def __init__(self, **options): self.proxy_host = options.get("http_proxy_host", None) if self.proxy_host: self.proxy_port = options.get("http_proxy_port", 0) self.auth = options.get("http_proxy_auth", None) self.no_proxy = options.get("http_no_proxy", None) self.proxy_protocol = options.get("proxy_type", "http") # Note: If timeout not specified, default python-socks timeout is 60 seconds self.proxy_timeout = options.get("http_proxy_timeout", None) if self.proxy_protocol not in [ "http", "socks4", "socks4a", "socks5", "socks5h", ]: raise ProxyError( "Only http, socks4, socks5 proxy protocols are supported" ) else: self.proxy_port = 0 self.auth = None self.no_proxy = None self.proxy_protocol = "http" def _start_proxied_socket(url: str, options, proxy) -> tuple: if not HAVE_PYTHON_SOCKS: raise WebSocketException( "Python Socks is needed for SOCKS proxying but is not available" ) hostname, port, resource, is_secure = parse_url(url) if proxy.proxy_protocol == "socks4": rdns = False proxy_type = ProxyType.SOCKS4 # socks4a sends DNS through proxy elif proxy.proxy_protocol == "socks4a": rdns = True proxy_type = ProxyType.SOCKS4 elif proxy.proxy_protocol == "socks5": rdns = False proxy_type = ProxyType.SOCKS5 # socks5h sends DNS through proxy elif proxy.proxy_protocol == "socks5h": rdns = True proxy_type = ProxyType.SOCKS5 ws_proxy = Proxy.create( proxy_type=proxy_type, host=proxy.proxy_host, port=int(proxy.proxy_port), username=proxy.auth[0] if proxy.auth else None, password=proxy.auth[1] if proxy.auth else None, rdns=rdns, ) sock = ws_proxy.connect(hostname, port, timeout=proxy.proxy_timeout) if is_secure: if HAVE_SSL: sock = _ssl_socket(sock, options.sslopt, hostname) else: raise WebSocketException("SSL not available.") return sock, (hostname, port, resource) def connect(url: str, options, proxy, socket): # Use _start_proxied_socket() only for socks4 or socks5 proxy # Use _tunnel() for http proxy # TODO: Use python-socks for http protocol also, to standardize flow if proxy.proxy_host and not socket and proxy.proxy_protocol != "http": return _start_proxied_socket(url, options, proxy) hostname, port_from_url, resource, is_secure = parse_url(url) if socket: return socket, (hostname, port_from_url, resource) addrinfo_list, need_tunnel, auth = _get_addrinfo_list( hostname, port_from_url, is_secure, proxy ) if not addrinfo_list: raise WebSocketException(f"Host not found.: {hostname}:{port_from_url}") sock = None try: sock = _open_socket(addrinfo_list, options.sockopt, options.timeout) if need_tunnel: sock = _tunnel(sock, hostname, port_from_url, auth) if is_secure: if HAVE_SSL: sock = _ssl_socket(sock, options.sslopt, hostname) else: raise WebSocketException("SSL not available.") return sock, (hostname, port_from_url, resource) except: if sock: sock.close() raise def _get_addrinfo_list(hostname, port: int, is_secure: bool, proxy) -> tuple: phost, pport, pauth = get_proxy_info( hostname, is_secure, proxy.proxy_host, proxy.proxy_port, proxy.auth, proxy.no_proxy, ) try: # when running on windows 10, getaddrinfo without socktype returns a socktype 0. # This generates an error exception: `_on_error: exception Socket type must be stream or datagram, not 0` # or `OSError: [Errno 22] Invalid argument` when creating socket. Force the socket type to SOCK_STREAM. if not phost: addrinfo_list = socket.getaddrinfo( hostname, port, 0, socket.SOCK_STREAM, socket.SOL_TCP ) return addrinfo_list, False, None else: pport = pport and pport or 80 # when running on windows 10, the getaddrinfo used above # returns a socktype 0. This generates an error exception: # _on_error: exception Socket type must be stream or datagram, not 0 # Force the socket type to SOCK_STREAM addrinfo_list = socket.getaddrinfo( phost, pport, 0, socket.SOCK_STREAM, socket.SOL_TCP ) return addrinfo_list, True, pauth except socket.gaierror as e: raise WebSocketAddressException(e) def _open_socket(addrinfo_list, sockopt, timeout): err = None for addrinfo in addrinfo_list: family, socktype, proto = addrinfo[:3] sock = socket.socket(family, socktype, proto) sock.settimeout(timeout) for opts in DEFAULT_SOCKET_OPTION: sock.setsockopt(*opts) for opts in sockopt: sock.setsockopt(*opts) address = addrinfo[4] err = None while not err: try: sock.connect(address) except socket.error as error: sock.close() error.remote_ip = str(address[0]) try: eConnRefused = ( errno.ECONNREFUSED, errno.WSAECONNREFUSED, errno.ENETUNREACH, ) except AttributeError: eConnRefused = (errno.ECONNREFUSED, errno.ENETUNREACH) if error.errno not in eConnRefused: raise error err = error continue else: break else: continue break else: if err: raise err return sock def _wrap_sni_socket(sock: socket.socket, sslopt: dict, hostname, check_hostname): context = sslopt.get("context", None) if not context: context = ssl.SSLContext(sslopt.get("ssl_version", ssl.PROTOCOL_TLS_CLIENT)) # Non default context need to manually enable SSLKEYLOGFILE support by setting the keylog_filename attribute. # For more details see also: # * https://docs.python.org/3.8/library/ssl.html?highlight=sslkeylogfile#context-creation # * https://docs.python.org/3.8/library/ssl.html?highlight=sslkeylogfile#ssl.SSLContext.keylog_filename context.keylog_filename = os.environ.get("SSLKEYLOGFILE", None) if sslopt.get("cert_reqs", ssl.CERT_NONE) != ssl.CERT_NONE: cafile = sslopt.get("ca_certs", None) capath = sslopt.get("ca_cert_path", None) if cafile or capath: context.load_verify_locations(cafile=cafile, capath=capath) elif hasattr(context, "load_default_certs"): context.load_default_certs(ssl.Purpose.SERVER_AUTH) if sslopt.get("certfile", None): context.load_cert_chain( sslopt["certfile"], sslopt.get("keyfile", None), sslopt.get("password", None), ) # Python 3.10 switch to PROTOCOL_TLS_CLIENT defaults to "cert_reqs = ssl.CERT_REQUIRED" and "check_hostname = True" # If both disabled, set check_hostname before verify_mode # see https://github.com/liris/websocket-client/commit/b96a2e8fa765753e82eea531adb19716b52ca3ca#commitcomment-10803153 if sslopt.get("cert_reqs", ssl.CERT_NONE) == ssl.CERT_NONE and not sslopt.get( "check_hostname", False ): context.check_hostname = False context.verify_mode = ssl.CERT_NONE else: context.check_hostname = sslopt.get("check_hostname", True) context.verify_mode = sslopt.get("cert_reqs", ssl.CERT_REQUIRED) if "ciphers" in sslopt: context.set_ciphers(sslopt["ciphers"]) if "cert_chain" in sslopt: certfile, keyfile, password = sslopt["cert_chain"] context.load_cert_chain(certfile, keyfile, password) if "ecdh_curve" in sslopt: context.set_ecdh_curve(sslopt["ecdh_curve"]) return context.wrap_socket( sock, do_handshake_on_connect=sslopt.get("do_handshake_on_connect", True), suppress_ragged_eofs=sslopt.get("suppress_ragged_eofs", True), server_hostname=hostname, ) def _ssl_socket(sock: socket.socket, user_sslopt: dict, hostname): sslopt: dict = dict(cert_reqs=ssl.CERT_REQUIRED) sslopt.update(user_sslopt) certPath = os.environ.get("WEBSOCKET_CLIENT_CA_BUNDLE") if ( certPath and os.path.isfile(certPath) and user_sslopt.get("ca_certs", None) is None ): sslopt["ca_certs"] = certPath elif ( certPath and os.path.isdir(certPath) and user_sslopt.get("ca_cert_path", None) is None ): sslopt["ca_cert_path"] = certPath if sslopt.get("server_hostname", None): hostname = sslopt["server_hostname"] check_hostname = sslopt.get("check_hostname", True) sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname) return sock def _tunnel(sock: socket.socket, host, port: int, auth) -> socket.socket: debug("Connecting proxy...") connect_header = f"CONNECT {host}:{port} HTTP/1.1\r\n" connect_header += f"Host: {host}:{port}\r\n" # TODO: support digest auth. if auth and auth[0]: auth_str = auth[0] if auth[1]: auth_str += f":{auth[1]}" encoded_str = base64encode(auth_str.encode()).strip().decode().replace("\n", "") connect_header += f"Proxy-Authorization: Basic {encoded_str}\r\n" connect_header += "\r\n" dump("request header", connect_header) send(sock, connect_header) try: status, resp_headers, status_message = read_headers(sock) except Exception as e: raise WebSocketProxyException(str(e)) if status != 200: raise WebSocketProxyException(f"failed CONNECT via proxy status: {status}") return sock def read_headers(sock: socket.socket) -> tuple: status = None status_message = None headers: dict = {} trace("--- response header ---") while True: line = recv_line(sock) line = line.decode("utf-8").strip() if not line: break trace(line) if not status: status_info = line.split(" ", 2) status = int(status_info[1]) if len(status_info) > 2: status_message = status_info[2] else: kv = line.split(":", 1) if len(kv) != 2: raise WebSocketException("Invalid header") key, value = kv if key.lower() == "set-cookie" and headers.get("set-cookie"): headers["set-cookie"] = headers.get("set-cookie") + "; " + value.strip() else: headers[key.lower()] = value.strip() trace("-----------------------") return status, headers, status_message websocket-client-1.7.0/websocket/_logging.py000066400000000000000000000042641453274240000211150ustar00rootroot00000000000000import logging """ _logging.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ _logger = logging.getLogger("websocket") try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record) -> None: pass _logger.addHandler(NullHandler()) _traceEnabled = False __all__ = [ "enableTrace", "dump", "error", "warning", "debug", "trace", "isEnabledForError", "isEnabledForDebug", "isEnabledForTrace", ] def enableTrace( traceable: bool, handler: logging.StreamHandler = logging.StreamHandler(), level: str = "DEBUG", ) -> None: """ Turn on/off the traceability. Parameters ---------- traceable: bool If set to True, traceability is enabled. """ global _traceEnabled _traceEnabled = traceable if traceable: _logger.addHandler(handler) _logger.setLevel(getattr(logging, level)) def dump(title: str, message: str) -> None: if _traceEnabled: _logger.debug(f"--- {title} ---") _logger.debug(message) _logger.debug("-----------------------") def error(msg: str) -> None: _logger.error(msg) def warning(msg: str) -> None: _logger.warning(msg) def debug(msg: str) -> None: _logger.debug(msg) def info(msg: str) -> None: _logger.info(msg) def trace(msg: str) -> None: if _traceEnabled: _logger.debug(msg) def isEnabledForError() -> bool: return _logger.isEnabledFor(logging.ERROR) def isEnabledForDebug() -> bool: return _logger.isEnabledFor(logging.DEBUG) def isEnabledForTrace() -> bool: return _traceEnabled websocket-client-1.7.0/websocket/_socket.py000066400000000000000000000116631453274240000207600ustar00rootroot00000000000000import errno import selectors import socket from typing import Union from ._exceptions import * from ._ssl_compat import * from ._utils import * """ _socket.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ DEFAULT_SOCKET_OPTION = [(socket.SOL_TCP, socket.TCP_NODELAY, 1)] if hasattr(socket, "SO_KEEPALIVE"): DEFAULT_SOCKET_OPTION.append((socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)) if hasattr(socket, "TCP_KEEPIDLE"): DEFAULT_SOCKET_OPTION.append((socket.SOL_TCP, socket.TCP_KEEPIDLE, 30)) if hasattr(socket, "TCP_KEEPINTVL"): DEFAULT_SOCKET_OPTION.append((socket.SOL_TCP, socket.TCP_KEEPINTVL, 10)) if hasattr(socket, "TCP_KEEPCNT"): DEFAULT_SOCKET_OPTION.append((socket.SOL_TCP, socket.TCP_KEEPCNT, 3)) _default_timeout = None __all__ = [ "DEFAULT_SOCKET_OPTION", "sock_opt", "setdefaulttimeout", "getdefaulttimeout", "recv", "recv_line", "send", ] class sock_opt: def __init__(self, sockopt: list, sslopt: dict) -> None: if sockopt is None: sockopt = [] if sslopt is None: sslopt = {} self.sockopt = sockopt self.sslopt = sslopt self.timeout = None def setdefaulttimeout(timeout: Union[int, float, None]) -> None: """ Set the global timeout setting to connect. Parameters ---------- timeout: int or float default socket timeout time (in seconds) """ global _default_timeout _default_timeout = timeout def getdefaulttimeout() -> Union[int, float, None]: """ Get default timeout Returns ---------- _default_timeout: int or float Return the global timeout setting (in seconds) to connect. """ return _default_timeout def recv(sock: socket.socket, bufsize: int) -> bytes: if not sock: raise WebSocketConnectionClosedException("socket is already closed.") def _recv(): try: return sock.recv(bufsize) except SSLWantReadError: pass except socket.error as exc: error_code = extract_error_code(exc) if error_code not in [errno.EAGAIN, errno.EWOULDBLOCK]: raise sel = selectors.DefaultSelector() sel.register(sock, selectors.EVENT_READ) r = sel.select(sock.gettimeout()) sel.close() if r: return sock.recv(bufsize) try: if sock.gettimeout() == 0: bytes_ = sock.recv(bufsize) else: bytes_ = _recv() except TimeoutError: raise WebSocketTimeoutException("Connection timed out") except socket.timeout as e: message = extract_err_message(e) raise WebSocketTimeoutException(message) except SSLError as e: message = extract_err_message(e) if isinstance(message, str) and "timed out" in message: raise WebSocketTimeoutException(message) else: raise if not bytes_: raise WebSocketConnectionClosedException("Connection to remote host was lost.") return bytes_ def recv_line(sock: socket.socket) -> bytes: line = [] while True: c = recv(sock, 1) line.append(c) if c == b"\n": break return b"".join(line) def send(sock: socket.socket, data: Union[bytes, str]) -> int: if isinstance(data, str): data = data.encode("utf-8") if not sock: raise WebSocketConnectionClosedException("socket is already closed.") def _send(): try: return sock.send(data) except SSLWantWriteError: pass except socket.error as exc: error_code = extract_error_code(exc) if error_code is None: raise if error_code not in [errno.EAGAIN, errno.EWOULDBLOCK]: raise sel = selectors.DefaultSelector() sel.register(sock, selectors.EVENT_WRITE) w = sel.select(sock.gettimeout()) sel.close() if w: return sock.send(data) try: if sock.gettimeout() == 0: return sock.send(data) else: return _send() except socket.timeout as e: message = extract_err_message(e) raise WebSocketTimeoutException(message) except Exception as e: message = extract_err_message(e) if isinstance(message, str) and "timed out" in message: raise WebSocketTimeoutException(message) else: raise websocket-client-1.7.0/websocket/_ssl_compat.py000066400000000000000000000020751453274240000216310ustar00rootroot00000000000000""" _ssl_compat.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["HAVE_SSL", "ssl", "SSLError", "SSLWantReadError", "SSLWantWriteError"] try: import ssl from ssl import SSLError, SSLWantReadError, SSLWantWriteError HAVE_SSL = True except ImportError: # dummy class of SSLError for environment without ssl support class SSLError(Exception): pass class SSLWantReadError(Exception): pass class SSLWantWriteError(Exception): pass ssl = None HAVE_SSL = False websocket-client-1.7.0/websocket/_url.py000066400000000000000000000117361453274240000202730ustar00rootroot00000000000000import os import socket import struct from typing import Optional from urllib.parse import unquote, urlparse """ _url.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["parse_url", "get_proxy_info"] def parse_url(url: str) -> tuple: """ parse url and the result is tuple of (hostname, port, resource path and the flag of secure mode) Parameters ---------- url: str url string. """ if ":" not in url: raise ValueError("url is invalid") scheme, url = url.split(":", 1) parsed = urlparse(url, scheme="http") if parsed.hostname: hostname = parsed.hostname else: raise ValueError("hostname is invalid") port = 0 if parsed.port: port = parsed.port is_secure = False if scheme == "ws": if not port: port = 80 elif scheme == "wss": is_secure = True if not port: port = 443 else: raise ValueError("scheme %s is invalid" % scheme) if parsed.path: resource = parsed.path else: resource = "/" if parsed.query: resource += f"?{parsed.query}" return hostname, port, resource, is_secure DEFAULT_NO_PROXY_HOST = ["localhost", "127.0.0.1"] def _is_ip_address(addr: str) -> bool: try: socket.inet_aton(addr) except socket.error: return False else: return True def _is_subnet_address(hostname: str) -> bool: try: addr, netmask = hostname.split("/") return _is_ip_address(addr) and 0 <= int(netmask) < 32 except ValueError: return False def _is_address_in_network(ip: str, net: str) -> bool: ipaddr: int = struct.unpack("!I", socket.inet_aton(ip))[0] netaddr, netmask = net.split("/") netaddr: int = struct.unpack("!I", socket.inet_aton(netaddr))[0] netmask = (0xFFFFFFFF << (32 - int(netmask))) & 0xFFFFFFFF return ipaddr & netmask == netaddr def _is_no_proxy_host(hostname: str, no_proxy: Optional[list]) -> bool: if not no_proxy: if v := os.environ.get("no_proxy", os.environ.get("NO_PROXY", "")).replace( " ", "" ): no_proxy = v.split(",") if not no_proxy: no_proxy = DEFAULT_NO_PROXY_HOST if "*" in no_proxy: return True if hostname in no_proxy: return True if _is_ip_address(hostname): return any( [ _is_address_in_network(hostname, subnet) for subnet in no_proxy if _is_subnet_address(subnet) ] ) for domain in [domain for domain in no_proxy if domain.startswith(".")]: if hostname.endswith(domain): return True return False def get_proxy_info( hostname: str, is_secure: bool, proxy_host: Optional[str] = None, proxy_port: int = 0, proxy_auth: Optional[tuple] = None, no_proxy: Optional[list] = None, proxy_type: str = "http", ) -> tuple: """ Try to retrieve proxy host and port from environment if not provided in options. Result is (proxy_host, proxy_port, proxy_auth). proxy_auth is tuple of username and password of proxy authentication information. Parameters ---------- hostname: str Websocket server name. is_secure: bool Is the connection secure? (wss) looks for "https_proxy" in env instead of "http_proxy" proxy_host: str http proxy host name. proxy_port: str or int http proxy port. no_proxy: list Whitelisted host names that don't use the proxy. proxy_auth: tuple HTTP proxy auth information. Tuple of username and password. Default is None. proxy_type: str Specify the proxy protocol (http, socks4, socks4a, socks5, socks5h). Default is "http". Use socks4a or socks5h if you want to send DNS requests through the proxy. """ if _is_no_proxy_host(hostname, no_proxy): return None, 0, None if proxy_host: port = proxy_port auth = proxy_auth return proxy_host, port, auth env_key = "https_proxy" if is_secure else "http_proxy" value = os.environ.get(env_key, os.environ.get(env_key.upper(), "")).replace( " ", "" ) if value: proxy = urlparse(value) auth = ( (unquote(proxy.username), unquote(proxy.password)) if proxy.username else None ) return proxy.hostname, proxy.port, auth return None, 0, None websocket-client-1.7.0/websocket/_utils.py000066400000000000000000000154611453274240000206300ustar00rootroot00000000000000from typing import Union """ _url.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["NoLock", "validate_utf8", "extract_err_message", "extract_error_code"] class NoLock: def __enter__(self) -> None: pass def __exit__(self, exc_type, exc_value, traceback) -> None: pass try: # If wsaccel is available we use compiled routines to validate UTF-8 # strings. from wsaccel.utf8validator import Utf8Validator def _validate_utf8(utfbytes: Union[str, bytes]) -> bool: result: bool = Utf8Validator().validate(utfbytes)[0] return result except ImportError: # UTF-8 validator # python implementation of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ _UTF8_ACCEPT = 0 _UTF8_REJECT = 12 _UTF8D = [ # The first part of the table maps bytes to character classes that # to reduce the size of the transition table and create bitmasks. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, # The second part is a transition table that maps a combination # of a state of the automaton and a character class to a state. 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 24, 12, 12, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, ] def _decode(state: int, codep: int, ch: int) -> tuple: tp = _UTF8D[ch] codep = ( (ch & 0x3F) | (codep << 6) if (state != _UTF8_ACCEPT) else (0xFF >> tp) & ch ) state = _UTF8D[256 + state + tp] return state, codep def _validate_utf8(utfbytes: Union[str, bytes]) -> bool: state = _UTF8_ACCEPT codep = 0 for i in utfbytes: state, codep = _decode(state, codep, int(i)) if state == _UTF8_REJECT: return False return True def validate_utf8(utfbytes: Union[str, bytes]) -> bool: """ validate utf8 byte string. utfbytes: utf byte string to check. return value: if valid utf8 string, return true. Otherwise, return false. """ return _validate_utf8(utfbytes) def extract_err_message(exception: Exception) -> Union[str, None]: if exception.args: exception_message: str = exception.args[0] return exception_message else: return None def extract_error_code(exception: Exception) -> Union[int, None]: if exception.args and len(exception.args) > 1: return exception.args[0] if isinstance(exception.args[0], int) else None websocket-client-1.7.0/websocket/_wsdump.py000077500000000000000000000155421453274240000210120ustar00rootroot00000000000000#!/usr/bin/env python3 """ wsdump.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import argparse import code import gzip import ssl import sys import threading import time import zlib from urllib.parse import urlparse import websocket try: import readline except ImportError: pass def get_encoding() -> str: encoding = getattr(sys.stdin, "encoding", "") if not encoding: return "utf-8" else: return encoding.lower() OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY) ENCODING = get_encoding() class VAction(argparse.Action): def __call__( self, parser: argparse.Namespace, args: tuple, values: str, option_string: str = None, ) -> None: if values is None: values = "1" try: values = int(values) except ValueError: values = values.count("v") + 1 setattr(args, self.dest, values) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool") parser.add_argument( "url", metavar="ws_url", help="websocket url. ex. ws://echo.websocket.events/" ) parser.add_argument("-p", "--proxy", help="proxy url. ex. http://127.0.0.1:8080") parser.add_argument( "-v", "--verbose", default=0, nargs="?", action=VAction, dest="verbose", help="set verbose mode. If set to 1, show opcode. " "If set to 2, enable to trace websocket module", ) parser.add_argument( "-n", "--nocert", action="store_true", help="Ignore invalid SSL cert" ) parser.add_argument("-r", "--raw", action="store_true", help="raw output") parser.add_argument("-s", "--subprotocols", nargs="*", help="Set subprotocols") parser.add_argument("-o", "--origin", help="Set origin") parser.add_argument( "--eof-wait", default=0, type=int, help="wait time(second) after 'EOF' received.", ) parser.add_argument("-t", "--text", help="Send initial text") parser.add_argument( "--timings", action="store_true", help="Print timings in seconds" ) parser.add_argument("--headers", help="Set custom headers. Use ',' as separator") return parser.parse_args() class RawInput: def raw_input(self, prompt: str = "") -> str: line = input(prompt) if ENCODING and ENCODING != "utf-8" and not isinstance(line, str): line = line.decode(ENCODING).encode("utf-8") elif isinstance(line, str): line = line.encode("utf-8") return line class InteractiveConsole(RawInput, code.InteractiveConsole): def write(self, data: str) -> None: sys.stdout.write("\033[2K\033[E") # sys.stdout.write("\n") sys.stdout.write("\033[34m< " + data + "\033[39m") sys.stdout.write("\n> ") sys.stdout.flush() def read(self) -> str: return self.raw_input("> ") class NonInteractive(RawInput): def write(self, data: str) -> None: sys.stdout.write(data) sys.stdout.write("\n") sys.stdout.flush() def read(self) -> str: return self.raw_input("") def main() -> None: start_time = time.time() args = parse_args() if args.verbose > 1: websocket.enableTrace(True) options = {} if args.proxy: p = urlparse(args.proxy) options["http_proxy_host"] = p.hostname options["http_proxy_port"] = p.port if args.origin: options["origin"] = args.origin if args.subprotocols: options["subprotocols"] = args.subprotocols opts = {} if args.nocert: opts = {"cert_reqs": ssl.CERT_NONE, "check_hostname": False} if args.headers: options["header"] = list(map(str.strip, args.headers.split(","))) ws = websocket.create_connection(args.url, sslopt=opts, **options) if args.raw: console = NonInteractive() else: console = InteractiveConsole() print("Press Ctrl+C to quit") def recv() -> tuple: try: frame = ws.recv_frame() except websocket.WebSocketException: return websocket.ABNF.OPCODE_CLOSE, "" if not frame: raise websocket.WebSocketException(f"Not a valid frame {frame}") elif frame.opcode in OPCODE_DATA: return frame.opcode, frame.data elif frame.opcode == websocket.ABNF.OPCODE_CLOSE: ws.send_close() return frame.opcode, "" elif frame.opcode == websocket.ABNF.OPCODE_PING: ws.pong(frame.data) return frame.opcode, frame.data return frame.opcode, frame.data def recv_ws() -> None: while True: opcode, data = recv() msg = None if opcode == websocket.ABNF.OPCODE_TEXT and isinstance(data, bytes): data = str(data, "utf-8") if ( isinstance(data, bytes) and len(data) > 2 and data[:2] == b"\037\213" ): # gzip magick try: data = "[gzip] " + str(gzip.decompress(data), "utf-8") except: pass elif isinstance(data, bytes): try: data = "[zlib] " + str( zlib.decompress(data, -zlib.MAX_WBITS), "utf-8" ) except: pass if isinstance(data, bytes): data = repr(data) if args.verbose: msg = f"{websocket.ABNF.OPCODE_MAP.get(opcode)}: {data}" else: msg = data if msg is not None: if args.timings: console.write(f"{time.time() - start_time}: {msg}") else: console.write(msg) if opcode == websocket.ABNF.OPCODE_CLOSE: break thread = threading.Thread(target=recv_ws) thread.daemon = True thread.start() if args.text: ws.send(args.text) while True: try: message = console.read() ws.send(message) except KeyboardInterrupt: return except EOFError: time.sleep(args.eof_wait) return if __name__ == "__main__": try: main() except Exception as e: print(e) websocket-client-1.7.0/websocket/py.typed000066400000000000000000000000001453274240000204350ustar00rootroot00000000000000websocket-client-1.7.0/websocket/tests/000077500000000000000000000000001453274240000201125ustar00rootroot00000000000000websocket-client-1.7.0/websocket/tests/__init__.py000066400000000000000000000000001453274240000222110ustar00rootroot00000000000000websocket-client-1.7.0/websocket/tests/data/000077500000000000000000000000001453274240000210235ustar00rootroot00000000000000websocket-client-1.7.0/websocket/tests/data/header01.txt000066400000000000000000000002431453274240000231540ustar00rootroot00000000000000HTTP/1.1 101 WebSocket Protocol Handshake Connection: Upgrade Upgrade: WebSocket Sec-WebSocket-Accept: Kxep+hNu9n51529fGidYu7a3wO0= some_header: something websocket-client-1.7.0/websocket/tests/data/header02.txt000066400000000000000000000002411453274240000231530ustar00rootroot00000000000000HTTP/1.1 101 WebSocket Protocol Handshake Connection: Upgrade Upgrade WebSocket Sec-WebSocket-Accept: Kxep+hNu9n51529fGidYu7a3wO0= some_header: something websocket-client-1.7.0/websocket/tests/data/header03.txt000066400000000000000000000003301453274240000231530ustar00rootroot00000000000000HTTP/1.1 101 WebSocket Protocol Handshake Connection: Upgrade, Keep-Alive Upgrade: WebSocket Sec-WebSocket-Accept: Kxep+hNu9n51529fGidYu7a3wO0= Set-Cookie: Token=ABCDE Set-Cookie: Token=FGHIJ some_header: something websocket-client-1.7.0/websocket/tests/echo-server.py000066400000000000000000000007501453274240000227100ustar00rootroot00000000000000#!/usr/bin/env python # From https://github.com/aaugustin/websockets/blob/main/example/echo.py import asyncio import os import websockets LOCAL_WS_SERVER_PORT = int(os.environ.get("LOCAL_WS_SERVER_PORT", "8765")) async def echo(websocket, path): async for message in websocket: await websocket.send(message) async def main(): async with websockets.serve(echo, "localhost", LOCAL_WS_SERVER_PORT): await asyncio.Future() # run forever asyncio.run(main()) websocket-client-1.7.0/websocket/tests/test_abnf.py000066400000000000000000000110621453274240000224310ustar00rootroot00000000000000# -*- coding: utf-8 -*- # import unittest import websocket as ws from websocket._abnf import * """ test_abnf.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class ABNFTest(unittest.TestCase): def testInit(self): a = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_PING) self.assertEqual(a.fin, 0) self.assertEqual(a.rsv1, 0) self.assertEqual(a.rsv2, 0) self.assertEqual(a.rsv3, 0) self.assertEqual(a.opcode, 9) self.assertEqual(a.data, "") a_bad = ABNF(0, 1, 0, 0, opcode=77) self.assertEqual(a_bad.rsv1, 1) self.assertEqual(a_bad.opcode, 77) def testValidate(self): a_invalid_ping = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_PING) self.assertRaises( ws._exceptions.WebSocketProtocolException, a_invalid_ping.validate, skip_utf8_validation=False, ) a_bad_rsv_value = ABNF(0, 1, 0, 0, opcode=ABNF.OPCODE_TEXT) self.assertRaises( ws._exceptions.WebSocketProtocolException, a_bad_rsv_value.validate, skip_utf8_validation=False, ) a_bad_opcode = ABNF(0, 0, 0, 0, opcode=77) self.assertRaises( ws._exceptions.WebSocketProtocolException, a_bad_opcode.validate, skip_utf8_validation=False, ) a_bad_close_frame = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_CLOSE, data=b"\x01") self.assertRaises( ws._exceptions.WebSocketProtocolException, a_bad_close_frame.validate, skip_utf8_validation=False, ) a_bad_close_frame_2 = ABNF( 0, 0, 0, 0, opcode=ABNF.OPCODE_CLOSE, data=b"\x01\x8a\xaa\xff\xdd" ) self.assertRaises( ws._exceptions.WebSocketProtocolException, a_bad_close_frame_2.validate, skip_utf8_validation=False, ) a_bad_close_frame_3 = ABNF( 0, 0, 0, 0, opcode=ABNF.OPCODE_CLOSE, data=b"\x03\xe7" ) self.assertRaises( ws._exceptions.WebSocketProtocolException, a_bad_close_frame_3.validate, skip_utf8_validation=True, ) def testMask(self): abnf_none_data = ABNF( 0, 0, 0, 0, opcode=ABNF.OPCODE_PING, mask_value=1, data=None ) bytes_val = b"aaaa" self.assertEqual(abnf_none_data._get_masked(bytes_val), bytes_val) abnf_str_data = ABNF( 0, 0, 0, 0, opcode=ABNF.OPCODE_PING, mask_value=1, data="a" ) self.assertEqual(abnf_str_data._get_masked(bytes_val), b"aaaa\x00") def testFormat(self): abnf_bad_rsv_bits = ABNF(2, 0, 0, 0, opcode=ABNF.OPCODE_TEXT) self.assertRaises(ValueError, abnf_bad_rsv_bits.format) abnf_bad_opcode = ABNF(0, 0, 0, 0, opcode=5) self.assertRaises(ValueError, abnf_bad_opcode.format) abnf_length_10 = ABNF(0, 0, 0, 0, opcode=ABNF.OPCODE_TEXT, data="abcdefghij") self.assertEqual(b"\x01", abnf_length_10.format()[0].to_bytes(1, "big")) self.assertEqual(b"\x8a", abnf_length_10.format()[1].to_bytes(1, "big")) self.assertEqual("fin=0 opcode=1 data=abcdefghij", abnf_length_10.__str__()) abnf_length_20 = ABNF( 0, 0, 0, 0, opcode=ABNF.OPCODE_BINARY, data="abcdefghijabcdefghij" ) self.assertEqual(b"\x02", abnf_length_20.format()[0].to_bytes(1, "big")) self.assertEqual(b"\x94", abnf_length_20.format()[1].to_bytes(1, "big")) abnf_no_mask = ABNF( 0, 0, 0, 0, opcode=ABNF.OPCODE_TEXT, mask_value=0, data=b"\x01\x8a\xcc" ) self.assertEqual(b"\x01\x03\x01\x8a\xcc", abnf_no_mask.format()) def testFrameBuffer(self): fb = frame_buffer(0, True) self.assertEqual(fb.recv, 0) self.assertEqual(fb.skip_utf8_validation, True) fb.clear self.assertEqual(fb.header, None) self.assertEqual(fb.length, None) self.assertEqual(fb.mask_value, None) self.assertEqual(fb.has_mask(), False) if __name__ == "__main__": unittest.main() websocket-client-1.7.0/websocket/tests/test_app.py000066400000000000000000000300351453274240000223040ustar00rootroot00000000000000# -*- coding: utf-8 -*- # import os import os.path import ssl import threading import unittest import websocket as ws """ test_app.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Skip test to access the internet unless TEST_WITH_INTERNET == 1 TEST_WITH_INTERNET = os.environ.get("TEST_WITH_INTERNET", "0") == "1" # Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1 LOCAL_WS_SERVER_PORT = os.environ.get("LOCAL_WS_SERVER_PORT", "-1") TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != "-1" TRACEABLE = True class WebSocketAppTest(unittest.TestCase): class NotSetYet: """A marker class for signalling that a value hasn't been set yet.""" def setUp(self): ws.enableTrace(TRACEABLE) WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet() WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet() def tearDown(self): WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet() WebSocketAppTest.on_error_data = WebSocketAppTest.NotSetYet() @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testKeepRunning(self): """A WebSocketApp should keep running as long as its self.keep_running is not False (in the boolean context). """ def on_open(self, *args, **kwargs): """Set the keep_running flag for later inspection and immediately close the connection. """ self.send("hello!") WebSocketAppTest.keep_running_open = self.keep_running self.keep_running = False def on_message(wsapp, message): print(message) self.close() def on_close(self, *args, **kwargs): """Set the keep_running flag for the test to use.""" WebSocketAppTest.keep_running_close = self.keep_running app = ws.WebSocketApp( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_open=on_open, on_close=on_close, on_message=on_message, ) app.run_forever() # @unittest.skipUnless(TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled") @unittest.skipUnless(False, "Test disabled for now (requires rel)") def testRunForeverDispatcher(self): """A WebSocketApp should keep running as long as its self.keep_running is not False (in the boolean context). """ def on_open(self, *args, **kwargs): """Send a message, receive, and send one more""" self.send("hello!") self.recv() self.send("goodbye!") def on_message(wsapp, message): print(message) self.close() app = ws.WebSocketApp( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_open=on_open, on_message=on_message, ) app.run_forever(dispatcher="Dispatcher") # doesn't work # app.run_forever(dispatcher=rel) # would work # rel.dispatch() @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testRunForeverTeardownCleanExit(self): """The WebSocketApp.run_forever() method should return `False` when the application ends gracefully.""" app = ws.WebSocketApp(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") threading.Timer(interval=0.2, function=app.close).start() teardown = app.run_forever() self.assertEqual(teardown, False) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testSockMaskKey(self): """A WebSocketApp should forward the received mask_key function down to the actual socket. """ def my_mask_key_func(): return "\x00\x00\x00\x00" app = ws.WebSocketApp( "wss://api-pub.bitfinex.com/ws/1", get_mask_key=my_mask_key_func ) # if numpy is installed, this assertion fail # Note: We can't use 'is' for comparing the functions directly, need to use 'id'. self.assertEqual(id(app.get_mask_key), id(my_mask_key_func)) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testInvalidPingIntervalPingTimeout(self): """Test exception handling if ping_interval < ping_timeout""" def on_ping(app, msg): print("Got a ping!") app.close() def on_pong(app, msg): print("Got a pong! No need to respond") app.close() app = ws.WebSocketApp( "wss://api-pub.bitfinex.com/ws/1", on_ping=on_ping, on_pong=on_pong ) self.assertRaises( ws.WebSocketException, app.run_forever, ping_interval=1, ping_timeout=2, sslopt={"cert_reqs": ssl.CERT_NONE}, ) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testPingInterval(self): """Test WebSocketApp proper ping functionality""" def on_ping(app, msg): print("Got a ping!") app.close() def on_pong(app, msg): print("Got a pong! No need to respond") app.close() app = ws.WebSocketApp( "wss://api-pub.bitfinex.com/ws/1", on_ping=on_ping, on_pong=on_pong ) app.run_forever( ping_interval=2, ping_timeout=1, sslopt={"cert_reqs": ssl.CERT_NONE} ) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testOpcodeClose(self): """Test WebSocketApp close opcode""" app = ws.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect") app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload") # This is commented out because the URL no longer responds in the expected way # @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") # def testOpcodeBinary(self): # """ Test WebSocketApp binary opcode # """ # app = ws.WebSocketApp('wss://streaming.vn.teslamotors.com/streaming/') # app.run_forever(ping_interval=2, ping_timeout=1, ping_payload="Ping payload") @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testBadPingInterval(self): """A WebSocketApp handling of negative ping_interval""" app = ws.WebSocketApp("wss://api-pub.bitfinex.com/ws/1") self.assertRaises( ws.WebSocketException, app.run_forever, ping_interval=-5, sslopt={"cert_reqs": ssl.CERT_NONE}, ) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testBadPingTimeout(self): """A WebSocketApp handling of negative ping_timeout""" app = ws.WebSocketApp("wss://api-pub.bitfinex.com/ws/1") self.assertRaises( ws.WebSocketException, app.run_forever, ping_timeout=-3, sslopt={"cert_reqs": ssl.CERT_NONE}, ) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testCloseStatusCode(self): """Test extraction of close frame status code and close reason in WebSocketApp""" def on_close(wsapp, close_status_code, close_msg): print("on_close reached") app = ws.WebSocketApp( "wss://tsock.us1.twilio.com/v3/wsconnect", on_close=on_close ) closeframe = ws.ABNF( opcode=ws.ABNF.OPCODE_CLOSE, data=b"\x03\xe8no-init-from-client" ) self.assertEqual([1000, "no-init-from-client"], app._get_close_args(closeframe)) closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b"") self.assertEqual([None, None], app._get_close_args(closeframe)) app2 = ws.WebSocketApp("wss://tsock.us1.twilio.com/v3/wsconnect") closeframe = ws.ABNF(opcode=ws.ABNF.OPCODE_CLOSE, data=b"") self.assertEqual([None, None], app2._get_close_args(closeframe)) self.assertRaises( ws.WebSocketConnectionClosedException, app.send, data="test if connection is closed", ) @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testCallbackFunctionException(self): """Test callback function exception handling""" exc = None passed_app = None def on_open(app): raise RuntimeError("Callback failed") def on_error(app, err): nonlocal passed_app passed_app = app nonlocal exc exc = err def on_pong(app, msg): app.close() app = ws.WebSocketApp( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_open=on_open, on_error=on_error, on_pong=on_pong, ) app.run_forever(ping_interval=2, ping_timeout=1) self.assertEqual(passed_app, app) self.assertIsInstance(exc, RuntimeError) self.assertEqual(str(exc), "Callback failed") @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testCallbackMethodException(self): """Test callback method exception handling""" class Callbacks: def __init__(self): self.exc = None self.passed_app = None self.app = ws.WebSocketApp( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_open=self.on_open, on_error=self.on_error, on_pong=self.on_pong, ) self.app.run_forever(ping_interval=2, ping_timeout=1) def on_open(self, app): raise RuntimeError("Callback failed") def on_error(self, app, err): self.passed_app = app self.exc = err def on_pong(self, app, msg): app.close() callbacks = Callbacks() self.assertEqual(callbacks.passed_app, callbacks.app) self.assertIsInstance(callbacks.exc, RuntimeError) self.assertEqual(str(callbacks.exc), "Callback failed") @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testReconnect(self): """Test reconnect""" pong_count = 0 exc = None def on_error(app, err): nonlocal exc exc = err def on_pong(app, msg): nonlocal pong_count pong_count += 1 if pong_count == 1: # First pong, shutdown socket, enforce read error app.sock.shutdown() if pong_count >= 2: # Got second pong after reconnect app.close() app = ws.WebSocketApp( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", on_pong=on_pong, on_error=on_error ) app.run_forever(ping_interval=2, ping_timeout=1, reconnect=3) self.assertEqual(pong_count, 2) self.assertIsInstance(exc, ws.WebSocketTimeoutException) self.assertEqual(str(exc), "ping/pong timed out") if __name__ == "__main__": unittest.main() websocket-client-1.7.0/websocket/tests/test_cookiejar.py000066400000000000000000000104501453274240000234710ustar00rootroot00000000000000import unittest from websocket._cookiejar import SimpleCookieJar """ test_cookiejar.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class CookieJarTest(unittest.TestCase): def testAdd(self): cookie_jar = SimpleCookieJar() cookie_jar.add("") self.assertFalse( cookie_jar.jar, "Cookie with no domain should not be added to the jar" ) cookie_jar = SimpleCookieJar() cookie_jar.add("a=b") self.assertFalse( cookie_jar.jar, "Cookie with no domain should not be added to the jar" ) cookie_jar = SimpleCookieJar() cookie_jar.add("a=b; domain=.abc") self.assertTrue(".abc" in cookie_jar.jar) cookie_jar = SimpleCookieJar() cookie_jar.add("a=b; domain=abc") self.assertTrue(".abc" in cookie_jar.jar) self.assertTrue("abc" not in cookie_jar.jar) cookie_jar = SimpleCookieJar() cookie_jar.add("a=b; c=d; domain=abc") self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") self.assertEqual(cookie_jar.get(None), "") cookie_jar = SimpleCookieJar() cookie_jar.add("a=b; c=d; domain=abc") cookie_jar.add("e=f; domain=abc") self.assertEqual(cookie_jar.get("abc"), "a=b; c=d; e=f") cookie_jar = SimpleCookieJar() cookie_jar.add("a=b; c=d; domain=abc") cookie_jar.add("e=f; domain=.abc") self.assertEqual(cookie_jar.get("abc"), "a=b; c=d; e=f") cookie_jar = SimpleCookieJar() cookie_jar.add("a=b; c=d; domain=abc") cookie_jar.add("e=f; domain=xyz") self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") self.assertEqual(cookie_jar.get("xyz"), "e=f") self.assertEqual(cookie_jar.get("something"), "") def testSet(self): cookie_jar = SimpleCookieJar() cookie_jar.set("a=b") self.assertFalse( cookie_jar.jar, "Cookie with no domain should not be added to the jar" ) cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; domain=.abc") self.assertTrue(".abc" in cookie_jar.jar) cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; domain=abc") self.assertTrue(".abc" in cookie_jar.jar) self.assertTrue("abc" not in cookie_jar.jar) cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; c=d; domain=abc") self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; c=d; domain=abc") cookie_jar.set("e=f; domain=abc") self.assertEqual(cookie_jar.get("abc"), "e=f") cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; c=d; domain=abc") cookie_jar.set("e=f; domain=.abc") self.assertEqual(cookie_jar.get("abc"), "e=f") cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; c=d; domain=abc") cookie_jar.set("e=f; domain=xyz") self.assertEqual(cookie_jar.get("abc"), "a=b; c=d") self.assertEqual(cookie_jar.get("xyz"), "e=f") self.assertEqual(cookie_jar.get("something"), "") def testGet(self): cookie_jar = SimpleCookieJar() cookie_jar.set("a=b; c=d; domain=abc.com") self.assertEqual(cookie_jar.get("abc.com"), "a=b; c=d") self.assertEqual(cookie_jar.get("x.abc.com"), "a=b; c=d") self.assertEqual(cookie_jar.get("abc.com.es"), "") self.assertEqual(cookie_jar.get("xabc.com"), "") cookie_jar.set("a=b; c=d; domain=.abc.com") self.assertEqual(cookie_jar.get("abc.com"), "a=b; c=d") self.assertEqual(cookie_jar.get("x.abc.com"), "a=b; c=d") self.assertEqual(cookie_jar.get("abc.com.es"), "") self.assertEqual(cookie_jar.get("xabc.com"), "") if __name__ == "__main__": unittest.main() websocket-client-1.7.0/websocket/tests/test_http.py000066400000000000000000000302131453274240000225010ustar00rootroot00000000000000# -*- coding: utf-8 -*- # import os import os.path import socket import ssl import unittest import websocket import websocket as ws from websocket._http import ( _get_addrinfo_list, _start_proxied_socket, _tunnel, connect, proxy_info, read_headers, ) """ test_http.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ try: from python_socks._errors import ProxyConnectionError, ProxyError, ProxyTimeoutError except: from websocket._http import ProxyConnectionError, ProxyError, ProxyTimeoutError # Skip test to access the internet unless TEST_WITH_INTERNET == 1 TEST_WITH_INTERNET = os.environ.get("TEST_WITH_INTERNET", "0") == "1" TEST_WITH_PROXY = os.environ.get("TEST_WITH_PROXY", "0") == "1" # Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1 LOCAL_WS_SERVER_PORT = os.environ.get("LOCAL_WS_SERVER_PORT", "-1") TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != "-1" class SockMock: def __init__(self): self.data = [] self.sent = [] def add_packet(self, data): self.data.append(data) def gettimeout(self): return None def recv(self, bufsize): if self.data: e = self.data.pop(0) if isinstance(e, Exception): raise e if len(e) > bufsize: self.data.insert(0, e[bufsize:]) return e[:bufsize] def send(self, data): self.sent.append(data) return len(data) def close(self): pass class HeaderSockMock(SockMock): def __init__(self, fname): SockMock.__init__(self) path = os.path.join(os.path.dirname(__file__), fname) with open(path, "rb") as f: self.add_packet(f.read()) class OptsList: def __init__(self): self.timeout = 1 self.sockopt = [] self.sslopt = {"cert_reqs": ssl.CERT_NONE} class HttpTest(unittest.TestCase): def testReadHeader(self): status, header, status_message = read_headers( HeaderSockMock("data/header01.txt") ) self.assertEqual(status, 101) self.assertEqual(header["connection"], "Upgrade") # header02.txt is intentionally malformed self.assertRaises( ws.WebSocketException, read_headers, HeaderSockMock("data/header02.txt") ) def testTunnel(self): self.assertRaises( ws.WebSocketProxyException, _tunnel, HeaderSockMock("data/header01.txt"), "example.com", 80, ("username", "password"), ) self.assertRaises( ws.WebSocketProxyException, _tunnel, HeaderSockMock("data/header02.txt"), "example.com", 80, ("username", "password"), ) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testConnect(self): # Not currently testing an actual proxy connection, so just check whether proxy errors are raised. This requires internet for a DNS lookup if ws._http.HAVE_PYTHON_SOCKS: # Need this check, otherwise case where python_socks is not installed triggers # websocket._exceptions.WebSocketException: Python Socks is needed for SOCKS proxying but is not available self.assertRaises( (ProxyTimeoutError, OSError), _start_proxied_socket, "wss://example.com", OptsList(), proxy_info( http_proxy_host="example.com", http_proxy_port="8080", proxy_type="socks4", http_proxy_timeout=1, ), ) self.assertRaises( (ProxyTimeoutError, OSError), _start_proxied_socket, "wss://example.com", OptsList(), proxy_info( http_proxy_host="example.com", http_proxy_port="8080", proxy_type="socks4a", http_proxy_timeout=1, ), ) self.assertRaises( (ProxyTimeoutError, OSError), _start_proxied_socket, "wss://example.com", OptsList(), proxy_info( http_proxy_host="example.com", http_proxy_port="8080", proxy_type="socks5", http_proxy_timeout=1, ), ) self.assertRaises( (ProxyTimeoutError, OSError), _start_proxied_socket, "wss://example.com", OptsList(), proxy_info( http_proxy_host="example.com", http_proxy_port="8080", proxy_type="socks5h", http_proxy_timeout=1, ), ) self.assertRaises( ProxyConnectionError, connect, "wss://example.com", OptsList(), proxy_info( http_proxy_host="127.0.0.1", http_proxy_port=9999, proxy_type="socks4", http_proxy_timeout=1, ), None, ) self.assertRaises( TypeError, _get_addrinfo_list, None, 80, True, proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="9999", proxy_type="http" ), ) self.assertRaises( TypeError, _get_addrinfo_list, None, 80, True, proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="9999", proxy_type="http" ), ) self.assertRaises( socket.timeout, connect, "wss://google.com", OptsList(), proxy_info( http_proxy_host="8.8.8.8", http_proxy_port=9999, proxy_type="http", http_proxy_timeout=1, ), None, ) self.assertEqual( connect( "wss://google.com", OptsList(), proxy_info( http_proxy_host="8.8.8.8", http_proxy_port=8080, proxy_type="http" ), True, ), (True, ("google.com", 443, "/")), ) # The following test fails on Mac OS with a gaierror, not an OverflowError # self.assertRaises(OverflowError, connect, "wss://example.com", OptsList(), proxy_info(http_proxy_host="127.0.0.1", http_proxy_port=99999, proxy_type="socks4", timeout=2), False) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") @unittest.skipUnless( TEST_WITH_PROXY, "This test requires a HTTP proxy to be running on port 8899" ) @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testProxyConnect(self): ws = websocket.WebSocket() ws.connect( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http", ) ws.send("Hello, Server") server_response = ws.recv() self.assertEqual(server_response, "Hello, Server") # self.assertEqual(_start_proxied_socket("wss://api.bitfinex.com/ws/2", OptsList(), proxy_info(http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http"))[1], ("api.bitfinex.com", 443, '/ws/2')) self.assertEqual( _get_addrinfo_list( "api.bitfinex.com", 443, True, proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http", ), ), ( socket.getaddrinfo( "127.0.0.1", 8899, 0, socket.SOCK_STREAM, socket.SOL_TCP ), True, None, ), ) self.assertEqual( connect( "wss://api.bitfinex.com/ws/2", OptsList(), proxy_info( http_proxy_host="127.0.0.1", http_proxy_port=8899, proxy_type="http" ), None, )[1], ("api.bitfinex.com", 443, "/ws/2"), ) # TODO: Test SOCKS4 and SOCK5 proxies with unit tests @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testSSLopt(self): ssloptions = { "check_hostname": False, "server_hostname": "ServerName", "ssl_version": ssl.PROTOCOL_TLS_CLIENT, "ciphers": "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:\ TLS_AES_128_GCM_SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:\ ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:\ ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:\ ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:\ ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ DHE-RSA-AES256-SHA256:ECDHE-ECDSA-AES128-SHA256:\ ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:\ ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA", "ecdh_curve": "prime256v1", } ws_ssl1 = websocket.WebSocket(sslopt=ssloptions) ws_ssl1.connect("wss://api.bitfinex.com/ws/2") ws_ssl1.send("Hello") ws_ssl1.close() ws_ssl2 = websocket.WebSocket(sslopt={"check_hostname": True}) ws_ssl2.connect("wss://api.bitfinex.com/ws/2") ws_ssl2.close def testProxyInfo(self): self.assertEqual( proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http" ).proxy_protocol, "http", ) self.assertRaises( ProxyError, proxy_info, http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="badval", ) self.assertEqual( proxy_info( http_proxy_host="example.com", http_proxy_port="8080", proxy_type="http" ).proxy_host, "example.com", ) self.assertEqual( proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http" ).proxy_port, "8080", ) self.assertEqual( proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http" ).auth, None, ) self.assertEqual( proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http", http_proxy_auth=("my_username123", "my_pass321"), ).auth[0], "my_username123", ) self.assertEqual( proxy_info( http_proxy_host="127.0.0.1", http_proxy_port="8080", proxy_type="http", http_proxy_auth=("my_username123", "my_pass321"), ).auth[1], "my_pass321", ) if __name__ == "__main__": unittest.main() websocket-client-1.7.0/websocket/tests/test_url.py000066400000000000000000000414631453274240000223350ustar00rootroot00000000000000# -*- coding: utf-8 -*- # import os import unittest from websocket._url import ( _is_address_in_network, _is_no_proxy_host, get_proxy_info, parse_url, ) """ test_url.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class UrlTest(unittest.TestCase): def test_address_in_network(self): self.assertTrue(_is_address_in_network("127.0.0.1", "127.0.0.0/8")) self.assertTrue(_is_address_in_network("127.1.0.1", "127.0.0.0/8")) self.assertFalse(_is_address_in_network("127.1.0.1", "127.0.0.0/24")) def testParseUrl(self): p = parse_url("ws://www.example.com/r") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 80) self.assertEqual(p[2], "/r") self.assertEqual(p[3], False) p = parse_url("ws://www.example.com/r/") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 80) self.assertEqual(p[2], "/r/") self.assertEqual(p[3], False) p = parse_url("ws://www.example.com/") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 80) self.assertEqual(p[2], "/") self.assertEqual(p[3], False) p = parse_url("ws://www.example.com") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 80) self.assertEqual(p[2], "/") self.assertEqual(p[3], False) p = parse_url("ws://www.example.com:8080/r") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/r") self.assertEqual(p[3], False) p = parse_url("ws://www.example.com:8080/") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/") self.assertEqual(p[3], False) p = parse_url("ws://www.example.com:8080") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/") self.assertEqual(p[3], False) p = parse_url("wss://www.example.com:8080/r") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/r") self.assertEqual(p[3], True) p = parse_url("wss://www.example.com:8080/r?key=value") self.assertEqual(p[0], "www.example.com") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/r?key=value") self.assertEqual(p[3], True) self.assertRaises(ValueError, parse_url, "http://www.example.com/r") p = parse_url("ws://[2a03:4000:123:83::3]/r") self.assertEqual(p[0], "2a03:4000:123:83::3") self.assertEqual(p[1], 80) self.assertEqual(p[2], "/r") self.assertEqual(p[3], False) p = parse_url("ws://[2a03:4000:123:83::3]:8080/r") self.assertEqual(p[0], "2a03:4000:123:83::3") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/r") self.assertEqual(p[3], False) p = parse_url("wss://[2a03:4000:123:83::3]/r") self.assertEqual(p[0], "2a03:4000:123:83::3") self.assertEqual(p[1], 443) self.assertEqual(p[2], "/r") self.assertEqual(p[3], True) p = parse_url("wss://[2a03:4000:123:83::3]:8080/r") self.assertEqual(p[0], "2a03:4000:123:83::3") self.assertEqual(p[1], 8080) self.assertEqual(p[2], "/r") self.assertEqual(p[3], True) class IsNoProxyHostTest(unittest.TestCase): def setUp(self): self.no_proxy = os.environ.get("no_proxy", None) if "no_proxy" in os.environ: del os.environ["no_proxy"] def tearDown(self): if self.no_proxy: os.environ["no_proxy"] = self.no_proxy elif "no_proxy" in os.environ: del os.environ["no_proxy"] def testMatchAll(self): self.assertTrue(_is_no_proxy_host("any.websocket.org", ["*"])) self.assertTrue(_is_no_proxy_host("192.168.0.1", ["*"])) self.assertTrue( _is_no_proxy_host("any.websocket.org", ["other.websocket.org", "*"]) ) os.environ["no_proxy"] = "*" self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) self.assertTrue(_is_no_proxy_host("192.168.0.1", None)) os.environ["no_proxy"] = "other.websocket.org, *" self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) def testIpAddress(self): self.assertTrue(_is_no_proxy_host("127.0.0.1", ["127.0.0.1"])) self.assertFalse(_is_no_proxy_host("127.0.0.2", ["127.0.0.1"])) self.assertTrue( _is_no_proxy_host("127.0.0.1", ["other.websocket.org", "127.0.0.1"]) ) self.assertFalse( _is_no_proxy_host("127.0.0.2", ["other.websocket.org", "127.0.0.1"]) ) os.environ["no_proxy"] = "127.0.0.1" self.assertTrue(_is_no_proxy_host("127.0.0.1", None)) self.assertFalse(_is_no_proxy_host("127.0.0.2", None)) os.environ["no_proxy"] = "other.websocket.org, 127.0.0.1" self.assertTrue(_is_no_proxy_host("127.0.0.1", None)) self.assertFalse(_is_no_proxy_host("127.0.0.2", None)) def testIpAddressInRange(self): self.assertTrue(_is_no_proxy_host("127.0.0.1", ["127.0.0.0/8"])) self.assertTrue(_is_no_proxy_host("127.0.0.2", ["127.0.0.0/8"])) self.assertFalse(_is_no_proxy_host("127.1.0.1", ["127.0.0.0/24"])) os.environ["no_proxy"] = "127.0.0.0/8" self.assertTrue(_is_no_proxy_host("127.0.0.1", None)) self.assertTrue(_is_no_proxy_host("127.0.0.2", None)) os.environ["no_proxy"] = "127.0.0.0/24" self.assertFalse(_is_no_proxy_host("127.1.0.1", None)) def testHostnameMatch(self): self.assertTrue(_is_no_proxy_host("my.websocket.org", ["my.websocket.org"])) self.assertTrue( _is_no_proxy_host( "my.websocket.org", ["other.websocket.org", "my.websocket.org"] ) ) self.assertFalse(_is_no_proxy_host("my.websocket.org", ["other.websocket.org"])) os.environ["no_proxy"] = "my.websocket.org" self.assertTrue(_is_no_proxy_host("my.websocket.org", None)) self.assertFalse(_is_no_proxy_host("other.websocket.org", None)) os.environ["no_proxy"] = "other.websocket.org, my.websocket.org" self.assertTrue(_is_no_proxy_host("my.websocket.org", None)) def testHostnameMatchDomain(self): self.assertTrue(_is_no_proxy_host("any.websocket.org", [".websocket.org"])) self.assertTrue(_is_no_proxy_host("my.other.websocket.org", [".websocket.org"])) self.assertTrue( _is_no_proxy_host( "any.websocket.org", ["my.websocket.org", ".websocket.org"] ) ) self.assertFalse(_is_no_proxy_host("any.websocket.com", [".websocket.org"])) os.environ["no_proxy"] = ".websocket.org" self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) self.assertTrue(_is_no_proxy_host("my.other.websocket.org", None)) self.assertFalse(_is_no_proxy_host("any.websocket.com", None)) os.environ["no_proxy"] = "my.websocket.org, .websocket.org" self.assertTrue(_is_no_proxy_host("any.websocket.org", None)) class ProxyInfoTest(unittest.TestCase): def setUp(self): self.http_proxy = os.environ.get("http_proxy", None) self.https_proxy = os.environ.get("https_proxy", None) self.no_proxy = os.environ.get("no_proxy", None) if "http_proxy" in os.environ: del os.environ["http_proxy"] if "https_proxy" in os.environ: del os.environ["https_proxy"] if "no_proxy" in os.environ: del os.environ["no_proxy"] def tearDown(self): if self.http_proxy: os.environ["http_proxy"] = self.http_proxy elif "http_proxy" in os.environ: del os.environ["http_proxy"] if self.https_proxy: os.environ["https_proxy"] = self.https_proxy elif "https_proxy" in os.environ: del os.environ["https_proxy"] if self.no_proxy: os.environ["no_proxy"] = self.no_proxy elif "no_proxy" in os.environ: del os.environ["no_proxy"] def testProxyFromArgs(self): self.assertEqual( get_proxy_info("echo.websocket.events", False, proxy_host="localhost"), ("localhost", 0, None), ) self.assertEqual( get_proxy_info( "echo.websocket.events", False, proxy_host="localhost", proxy_port=3128 ), ("localhost", 3128, None), ) self.assertEqual( get_proxy_info("echo.websocket.events", True, proxy_host="localhost"), ("localhost", 0, None), ) self.assertEqual( get_proxy_info( "echo.websocket.events", True, proxy_host="localhost", proxy_port=3128 ), ("localhost", 3128, None), ) self.assertEqual( get_proxy_info( "echo.websocket.events", False, proxy_host="localhost", proxy_auth=("a", "b"), ), ("localhost", 0, ("a", "b")), ) self.assertEqual( get_proxy_info( "echo.websocket.events", False, proxy_host="localhost", proxy_port=3128, proxy_auth=("a", "b"), ), ("localhost", 3128, ("a", "b")), ) self.assertEqual( get_proxy_info( "echo.websocket.events", True, proxy_host="localhost", proxy_auth=("a", "b"), ), ("localhost", 0, ("a", "b")), ) self.assertEqual( get_proxy_info( "echo.websocket.events", True, proxy_host="localhost", proxy_port=3128, proxy_auth=("a", "b"), ), ("localhost", 3128, ("a", "b")), ) self.assertEqual( get_proxy_info( "echo.websocket.events", True, proxy_host="localhost", proxy_port=3128, no_proxy=["example.com"], proxy_auth=("a", "b"), ), ("localhost", 3128, ("a", "b")), ) self.assertEqual( get_proxy_info( "echo.websocket.events", True, proxy_host="localhost", proxy_port=3128, no_proxy=["echo.websocket.events"], proxy_auth=("a", "b"), ), (None, 0, None), ) def testProxyFromEnv(self): os.environ["http_proxy"] = "http://localhost/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", None, None) ) os.environ["http_proxy"] = "http://localhost:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", 3128, None) ) os.environ["http_proxy"] = "http://localhost/" os.environ["https_proxy"] = "http://localhost2/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", None, None) ) os.environ["http_proxy"] = "http://localhost:3128/" os.environ["https_proxy"] = "http://localhost2:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", 3128, None) ) os.environ["http_proxy"] = "http://localhost/" os.environ["https_proxy"] = "http://localhost2/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", None, None) ) os.environ["http_proxy"] = "http://localhost:3128/" os.environ["https_proxy"] = "http://localhost2:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", 3128, None) ) os.environ["http_proxy"] = "" os.environ["https_proxy"] = "http://localhost2/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", None, None) ) self.assertEqual( get_proxy_info("echo.websocket.events", False), (None, 0, None) ) os.environ["http_proxy"] = "" os.environ["https_proxy"] = "http://localhost2:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", 3128, None) ) self.assertEqual( get_proxy_info("echo.websocket.events", False), (None, 0, None) ) os.environ["http_proxy"] = "http://localhost/" os.environ["https_proxy"] = "" self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", None, None) ) os.environ["http_proxy"] = "http://localhost:3128/" os.environ["https_proxy"] = "" self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", 3128, None) ) os.environ["http_proxy"] = "http://a:b@localhost/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", None, ("a", "b")), ) os.environ["http_proxy"] = "http://a:b@localhost:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", 3128, ("a", "b")), ) os.environ["http_proxy"] = "http://a:b@localhost/" os.environ["https_proxy"] = "http://a:b@localhost2/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", None, ("a", "b")), ) os.environ["http_proxy"] = "http://a:b@localhost:3128/" os.environ["https_proxy"] = "http://a:b@localhost2:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", False), ("localhost", 3128, ("a", "b")), ) os.environ["http_proxy"] = "http://a:b@localhost/" os.environ["https_proxy"] = "http://a:b@localhost2/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", None, ("a", "b")), ) os.environ["http_proxy"] = "http://a:b@localhost:3128/" os.environ["https_proxy"] = "http://a:b@localhost2:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", 3128, ("a", "b")), ) os.environ[ "http_proxy" ] = "http://john%40example.com:P%40SSWORD@localhost:3128/" os.environ[ "https_proxy" ] = "http://john%40example.com:P%40SSWORD@localhost2:3128/" self.assertEqual( get_proxy_info("echo.websocket.events", True), ("localhost2", 3128, ("john@example.com", "P@SSWORD")), ) os.environ["http_proxy"] = "http://a:b@localhost/" os.environ["https_proxy"] = "http://a:b@localhost2/" os.environ["no_proxy"] = "example1.com,example2.com" self.assertEqual( get_proxy_info("example.1.com", True), ("localhost2", None, ("a", "b")) ) os.environ["http_proxy"] = "http://a:b@localhost:3128/" os.environ["https_proxy"] = "http://a:b@localhost2:3128/" os.environ["no_proxy"] = "example1.com,example2.com, echo.websocket.events" self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) os.environ["http_proxy"] = "http://a:b@localhost:3128/" os.environ["https_proxy"] = "http://a:b@localhost2:3128/" os.environ["no_proxy"] = "example1.com,example2.com, .websocket.events" self.assertEqual(get_proxy_info("echo.websocket.events", True), (None, 0, None)) os.environ["http_proxy"] = "http://a:b@localhost:3128/" os.environ["https_proxy"] = "http://a:b@localhost2:3128/" os.environ["no_proxy"] = "127.0.0.0/8, 192.168.0.0/16" self.assertEqual(get_proxy_info("127.0.0.1", False), (None, 0, None)) self.assertEqual(get_proxy_info("192.168.1.1", False), (None, 0, None)) if __name__ == "__main__": unittest.main() websocket-client-1.7.0/websocket/tests/test_websocket.py000066400000000000000000000440021453274240000235110ustar00rootroot00000000000000# -*- coding: utf-8 -*- # import os import os.path import socket import unittest from base64 import decodebytes as base64decode import websocket as ws from websocket._handshake import _create_sec_websocket_key from websocket._handshake import _validate as _validate_header from websocket._http import read_headers from websocket._utils import validate_utf8 """ test_websocket.py websocket - WebSocket client library for Python Copyright 2023 engn33r Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ try: import ssl from ssl import SSLError except ImportError: # dummy class of SSLError for ssl none-support environment. class SSLError(Exception): pass # Skip test to access the internet unless TEST_WITH_INTERNET == 1 TEST_WITH_INTERNET = os.environ.get("TEST_WITH_INTERNET", "0") == "1" # Skip tests relying on local websockets server unless LOCAL_WS_SERVER_PORT != -1 LOCAL_WS_SERVER_PORT = os.environ.get("LOCAL_WS_SERVER_PORT", "-1") TEST_WITH_LOCAL_SERVER = LOCAL_WS_SERVER_PORT != "-1" TRACEABLE = True def create_mask_key(_): return "abcd" class SockMock: def __init__(self): self.data = [] self.sent = [] def add_packet(self, data): self.data.append(data) def gettimeout(self): return None def recv(self, bufsize): if self.data: e = self.data.pop(0) if isinstance(e, Exception): raise e if len(e) > bufsize: self.data.insert(0, e[bufsize:]) return e[:bufsize] def send(self, data): self.sent.append(data) return len(data) def close(self): pass class HeaderSockMock(SockMock): def __init__(self, fname): SockMock.__init__(self) path = os.path.join(os.path.dirname(__file__), fname) with open(path, "rb") as f: self.add_packet(f.read()) class WebSocketTest(unittest.TestCase): def setUp(self): ws.enableTrace(TRACEABLE) def tearDown(self): pass def testDefaultTimeout(self): self.assertEqual(ws.getdefaulttimeout(), None) ws.setdefaulttimeout(10) self.assertEqual(ws.getdefaulttimeout(), 10) ws.setdefaulttimeout(None) def testWSKey(self): key = _create_sec_websocket_key() self.assertTrue(key != 24) self.assertTrue("¥n" not in key) def testNonce(self): """WebSocket key should be a random 16-byte nonce.""" key = _create_sec_websocket_key() nonce = base64decode(key.encode("utf-8")) self.assertEqual(16, len(nonce)) def testWsUtils(self): key = "c6b8hTg4EeGb2gQMztV1/g==" required_header = { "upgrade": "websocket", "connection": "upgrade", "sec-websocket-accept": "Kxep+hNu9n51529fGidYu7a3wO0=", } self.assertEqual(_validate_header(required_header, key, None), (True, None)) header = required_header.copy() header["upgrade"] = "http" self.assertEqual(_validate_header(header, key, None), (False, None)) del header["upgrade"] self.assertEqual(_validate_header(header, key, None), (False, None)) header = required_header.copy() header["connection"] = "something" self.assertEqual(_validate_header(header, key, None), (False, None)) del header["connection"] self.assertEqual(_validate_header(header, key, None), (False, None)) header = required_header.copy() header["sec-websocket-accept"] = "something" self.assertEqual(_validate_header(header, key, None), (False, None)) del header["sec-websocket-accept"] self.assertEqual(_validate_header(header, key, None), (False, None)) header = required_header.copy() header["sec-websocket-protocol"] = "sub1" self.assertEqual( _validate_header(header, key, ["sub1", "sub2"]), (True, "sub1") ) # This case will print out a logging error using the error() function, but that is expected self.assertEqual(_validate_header(header, key, ["sub2", "sub3"]), (False, None)) header = required_header.copy() header["sec-websocket-protocol"] = "sUb1" self.assertEqual( _validate_header(header, key, ["Sub1", "suB2"]), (True, "sub1") ) header = required_header.copy() # This case will print out a logging error using the error() function, but that is expected self.assertEqual(_validate_header(header, key, ["Sub1", "suB2"]), (False, None)) def testReadHeader(self): status, header, status_message = read_headers( HeaderSockMock("data/header01.txt") ) self.assertEqual(status, 101) self.assertEqual(header["connection"], "Upgrade") status, header, status_message = read_headers( HeaderSockMock("data/header03.txt") ) self.assertEqual(status, 101) self.assertEqual(header["connection"], "Upgrade, Keep-Alive") HeaderSockMock("data/header02.txt") self.assertRaises( ws.WebSocketException, read_headers, HeaderSockMock("data/header02.txt") ) def testSend(self): # TODO: add longer frame data sock = ws.WebSocket() sock.set_mask_key(create_mask_key) s = sock.sock = HeaderSockMock("data/header01.txt") sock.send("Hello") self.assertEqual(s.sent[0], b"\x81\x85abcd)\x07\x0f\x08\x0e") sock.send("こんにちは") self.assertEqual( s.sent[1], b"\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc", ) # sock.send("x" * 5000) # self.assertEqual(s.sent[1], b'\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc") self.assertEqual(sock.send_binary(b"1111111111101"), 19) def testRecv(self): # TODO: add longer frame data sock = ws.WebSocket() s = sock.sock = SockMock() something = ( b"\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc" ) s.add_packet(something) data = sock.recv() self.assertEqual(data, "こんにちは") s.add_packet(b"\x81\x85abcd)\x07\x0f\x08\x0e") data = sock.recv() self.assertEqual(data, "Hello") @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testIter(self): count = 2 s = ws.create_connection("wss://api.bitfinex.com/ws/2") s.send('{"event": "subscribe", "channel": "ticker"}') for _ in s: count -= 1 if count == 0: break @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testNext(self): sock = ws.create_connection("wss://api.bitfinex.com/ws/2") self.assertEqual(str, type(next(sock))) def testInternalRecvStrict(self): sock = ws.WebSocket() s = sock.sock = SockMock() s.add_packet(b"foo") s.add_packet(socket.timeout()) s.add_packet(b"bar") # s.add_packet(SSLError("The read operation timed out")) s.add_packet(b"baz") with self.assertRaises(ws.WebSocketTimeoutException): sock.frame_buffer.recv_strict(9) # with self.assertRaises(SSLError): # data = sock._recv_strict(9) data = sock.frame_buffer.recv_strict(9) self.assertEqual(data, b"foobarbaz") with self.assertRaises(ws.WebSocketConnectionClosedException): sock.frame_buffer.recv_strict(1) def testRecvTimeout(self): sock = ws.WebSocket() s = sock.sock = SockMock() s.add_packet(b"\x81") s.add_packet(socket.timeout()) s.add_packet(b"\x8dabcd\x29\x07\x0f\x08\x0e") s.add_packet(socket.timeout()) s.add_packet(b"\x4e\x43\x33\x0e\x10\x0f\x00\x40") with self.assertRaises(ws.WebSocketTimeoutException): sock.recv() with self.assertRaises(ws.WebSocketTimeoutException): sock.recv() data = sock.recv() self.assertEqual(data, "Hello, World!") with self.assertRaises(ws.WebSocketConnectionClosedException): sock.recv() def testRecvWithSimpleFragmentation(self): sock = ws.WebSocket() s = sock.sock = SockMock() # OPCODE=TEXT, FIN=0, MSG="Brevity is " s.add_packet(b"\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") # OPCODE=CONT, FIN=1, MSG="the soul of wit" s.add_packet(b"\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17") data = sock.recv() self.assertEqual(data, "Brevity is the soul of wit") with self.assertRaises(ws.WebSocketConnectionClosedException): sock.recv() def testRecvWithFireEventOfFragmentation(self): sock = ws.WebSocket(fire_cont_frame=True) s = sock.sock = SockMock() # OPCODE=TEXT, FIN=0, MSG="Brevity is " s.add_packet(b"\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") # OPCODE=CONT, FIN=0, MSG="Brevity is " s.add_packet(b"\x00\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") # OPCODE=CONT, FIN=1, MSG="the soul of wit" s.add_packet(b"\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17") _, data = sock.recv_data() self.assertEqual(data, b"Brevity is ") _, data = sock.recv_data() self.assertEqual(data, b"Brevity is ") _, data = sock.recv_data() self.assertEqual(data, b"the soul of wit") # OPCODE=CONT, FIN=0, MSG="Brevity is " s.add_packet(b"\x80\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C") with self.assertRaises(ws.WebSocketException): sock.recv_data() with self.assertRaises(ws.WebSocketConnectionClosedException): sock.recv() def testClose(self): sock = ws.WebSocket() sock.connected = True sock.close sock = ws.WebSocket() s = sock.sock = SockMock() sock.connected = True s.add_packet(b"\x88\x80\x17\x98p\x84") sock.recv() self.assertEqual(sock.connected, False) def testRecvContFragmentation(self): sock = ws.WebSocket() s = sock.sock = SockMock() # OPCODE=CONT, FIN=1, MSG="the soul of wit" s.add_packet(b"\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17") self.assertRaises(ws.WebSocketException, sock.recv) def testRecvWithProlongedFragmentation(self): sock = ws.WebSocket() s = sock.sock = SockMock() # OPCODE=TEXT, FIN=0, MSG="Once more unto the breach, " s.add_packet( b"\x01\x9babcd.\x0c\x00\x01A\x0f\x0c\x16\x04B\x16\n\x15\rC\x10\t\x07C\x06\x13\x07\x02\x07\tNC" ) # OPCODE=CONT, FIN=0, MSG="dear friends, " s.add_packet(b"\x00\x8eabcd\x05\x07\x02\x16A\x04\x11\r\x04\x0c\x07\x17MB") # OPCODE=CONT, FIN=1, MSG="once more" s.add_packet(b"\x80\x89abcd\x0e\x0c\x00\x01A\x0f\x0c\x16\x04") data = sock.recv() self.assertEqual(data, "Once more unto the breach, dear friends, once more") with self.assertRaises(ws.WebSocketConnectionClosedException): sock.recv() def testRecvWithFragmentationAndControlFrame(self): sock = ws.WebSocket() sock.set_mask_key(create_mask_key) s = sock.sock = SockMock() # OPCODE=TEXT, FIN=0, MSG="Too much " s.add_packet(b"\x01\x89abcd5\r\x0cD\x0c\x17\x00\x0cA") # OPCODE=PING, FIN=1, MSG="Please PONG this" s.add_packet(b"\x89\x90abcd1\x0e\x06\x05\x12\x07C4.,$D\x15\n\n\x17") # OPCODE=CONT, FIN=1, MSG="of a good thing" s.add_packet(b"\x80\x8fabcd\x0e\x04C\x05A\x05\x0c\x0b\x05B\x17\x0c\x08\x0c\x04") data = sock.recv() self.assertEqual(data, "Too much of a good thing") with self.assertRaises(ws.WebSocketConnectionClosedException): sock.recv() self.assertEqual( s.sent[0], b"\x8a\x90abcd1\x0e\x06\x05\x12\x07C4.,$D\x15\n\n\x17" ) @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testWebSocket(self): s = ws.create_connection(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") self.assertNotEqual(s, None) s.send("Hello, World") result = s.next() s.fileno() self.assertEqual(result, "Hello, World") s.send("こにゃにゃちは、世界") result = s.recv() self.assertEqual(result, "こにゃにゃちは、世界") self.assertRaises(ValueError, s.send_close, -1, "") s.close() @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testPingPong(self): s = ws.create_connection(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") self.assertNotEqual(s, None) s.ping("Hello") s.pong("Hi") s.close() @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testSupportRedirect(self): s = ws.WebSocket() self.assertRaises( ws._exceptions.WebSocketBadStatusException, s.connect, "ws://google.com/" ) # Need to find a URL that has a redirect code leading to a websocket @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testSecureWebSocket(self): import ssl s = ws.create_connection("wss://api.bitfinex.com/ws/2") self.assertNotEqual(s, None) self.assertTrue(isinstance(s.sock, ssl.SSLSocket)) self.assertEqual(s.getstatus(), 101) self.assertNotEqual(s.getheaders(), None) s.settimeout(10) self.assertEqual(s.gettimeout(), 10) self.assertEqual(s.getsubprotocol(), None) s.abort() @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testWebSocketWithCustomHeader(self): s = ws.create_connection( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", headers={"User-Agent": "PythonWebsocketClient"}, ) self.assertNotEqual(s, None) self.assertEqual(s.getsubprotocol(), None) s.send("Hello, World") result = s.recv() self.assertEqual(result, "Hello, World") self.assertRaises(ValueError, s.close, -1, "") s.close() @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testAfterClose(self): s = ws.create_connection(f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}") self.assertNotEqual(s, None) s.close() self.assertRaises(ws.WebSocketConnectionClosedException, s.send, "Hello") self.assertRaises(ws.WebSocketConnectionClosedException, s.recv) class SockOptTest(unittest.TestCase): @unittest.skipUnless( TEST_WITH_LOCAL_SERVER, "Tests using local websocket server are disabled" ) def testSockOpt(self): sockopt = ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),) s = ws.create_connection( f"ws://127.0.0.1:{LOCAL_WS_SERVER_PORT}", sockopt=sockopt ) self.assertNotEqual( s.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0 ) s.close() class UtilsTest(unittest.TestCase): def testUtf8Validator(self): state = validate_utf8(b"\xf0\x90\x80\x80") self.assertEqual(state, True) state = validate_utf8( b"\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5\xed\xa0\x80edited" ) self.assertEqual(state, False) state = validate_utf8(b"") self.assertEqual(state, True) class HandshakeTest(unittest.TestCase): @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def test_http_SSL(self): websock1 = ws.WebSocket( sslopt={"cert_chain": ssl.get_default_verify_paths().capath}, enable_multithread=False, ) self.assertRaises(ValueError, websock1.connect, "wss://api.bitfinex.com/ws/2") websock2 = ws.WebSocket(sslopt={"certfile": "myNonexistentCertFile"}) self.assertRaises( FileNotFoundError, websock2.connect, "wss://api.bitfinex.com/ws/2" ) @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled") def testManualHeaders(self): websock3 = ws.WebSocket( sslopt={ "ca_certs": ssl.get_default_verify_paths().cafile, "ca_cert_path": ssl.get_default_verify_paths().capath, } ) self.assertRaises( ws._exceptions.WebSocketBadStatusException, websock3.connect, "wss://api.bitfinex.com/ws/2", cookie="chocolate", origin="testing_websockets.com", host="echo.websocket.events/websocket-client-test", subprotocols=["testproto"], connection="Upgrade", header={ "CustomHeader1": "123", "Cookie": "TestValue", "Sec-WebSocket-Key": "k9kFAUWNAMmf5OEMfTlOEA==", "Sec-WebSocket-Protocol": "newprotocol", }, ) def testIPv6(self): websock2 = ws.WebSocket() self.assertRaises(ValueError, websock2.connect, "2001:4860:4860::8888") def testBadURLs(self): websock3 = ws.WebSocket() self.assertRaises(ValueError, websock3.connect, "ws//example.com") self.assertRaises( ws.WebSocketAddressException, websock3.connect, "ws://example" ) self.assertRaises(ValueError, websock3.connect, "example.com") if __name__ == "__main__": unittest.main()