Python websockets subprotocol как использовать
Перейти к содержимому

Python websockets subprotocol как использовать

  • автор:

Python websockets subprotocol как использовать

websocket-client module is WebSocket client for python. This provide the low level APIs for WebSocket. All APIs are the synchronous functions.

websocket-client supports only hybi-13.

License

  • LGPL

Installation

This module is tested on Python 2.7 and Python 3.4+.

Type “python setup.py install” or “pip install websocket-client” to install.

from v0.16.0, we can install by “pip install websocket-client” for Python 3.

This module depends on

  • six
  • backports.ssl_match_hostname for Python 2.x

performance

“send” method is too slow on pure python. If you want to get better performace, please install numpy or wsaccel. You can get the best performance from numpy.

How about Python 3

Now, we support Python 3 on single source code from version 0.14.0. Thanks, @battlemidget and @ralphbean.

HTTP Proxy

Support websocket access via http proxy. The proxy server must allow “CONNECT” method to websocket port. Default squid setting is “ALLOWED TO CONNECT ONLY HTTPS PORT”.

Current implementation of websocket-client is using “CONNECT” method via proxy.

Examples

Long-lived connection

This example is similar to how WebSocket code looks in browsers using JavaScript.

Short-lived one-off send-receive

This is if you want to communicate a short message and disconnect immediately when done.

If you want to customize socket options, set sockopt.

More advanced: Custom class

You can also write your own class for the connection, if you want to handle the nitty-gritty details yourself.

How to disable ssl cert verification?

How to disable hostname verification.

Please set sslopt to <“check_hostname”: False>. (since v0.18.0)

How to enable SNI?

SNI support is available for Python 2.7.9+ and 3.2+. It will be enabled automatically whenever possible.

Sub Protocols.

The server needs to support sub protocols, please set the subprotocol like this.

wsdump.py

wsdump.py is simple WebSocket test(debug) tool.

sample for echo.websocket.org:

Usage

WebSocket Simple Dump Tool

positional arguments: ws_url websocket url. ex. ws://echo.websocket.org/ optional arguments:

-h, —help show this help message and exit

WebSocketApp

-v VERBOSE , —verbose VERBOSE
set verbose mode. If set to 1, show opcode. If set to 2, enable to trace websocket module

Intelligent Recommendation

JavaWeb + Websocket implementation client

Recently, a JavaWeb project is needed, but there is no connection with the database connection through WebSocket communication and server-side data interaction. I have searched a lot, and most of the .

java websocket client

WebSocket is a new protocol for H5, generally used for front end, but in actual projects, we need to use Java code to get real-time running data for some devices, and processed the front interface to .

JavaScript client WebSocket example

[Websocket] QT client

If you still don’t understand WebSocket, you can refer to my previous blog:[Websocket] Getting Started (JS) QWEBSocket provided by Qt can be used for both client applications, or for server applicatio.

Implement WebSocket client in Unity

More Recommendation

Java implementation WebSocket client

POM reliance Fastjson is used to send JSON data, you can use your own use .

C # Websocket Client underdere

GitHub Address: https://github.com/JF-ACER/websocketClient.git Implementation and official client library: Source code directory: Foreword: Duplex Communication Websocket client is generally JS, if yo.

WebSocket uses (client)

First, introduction WebSocketIs a singleTCPCarry on the connectionFull-duplexCommunication protocol. WebSocket Communication Agreement is in 2011IETFIt is customized to standard RFC 6455 and replenish.

Java WebSocket client

Use Java-WebSocket to do clients in Java POM file Client implementation Maintain monitoring connection.

Web | HTML WebSocket Client

Web | HTML WebSocket Client Simply record it, and forget where the reference link is. Essence Essence.

Name already in use

websocket-client / docs / source / examples.rst

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

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

WebSocketApp example

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.

The output you will see will look something like this:

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

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
    • 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

    WebSocketApp common headers example

    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.

    WebSocketApp subprotocols example

    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

    WebSocketApp suppress origin example

    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

    WebSocketApp custom headers example

    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.

    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

    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

    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

    WebSocket SOCKS4 (or SOCKS5) proxy example

    WebSocketApp proxy example

    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.

    Other socket types can also be used. The following example is for a AF_INET (IP address) 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.

    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.

    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 .

    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<Debug and Logging Options>` 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

    WebSocketApp sending close() status code example

    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<Debug and Logging Options>` 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

    WebSocketApp receiving close status code example

    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

    WebSocketApp custom masking key code example

    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

    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.

    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

    The examples are found in the README and are copied here for sphinx doctests to verify they run without errors.

    Django Channels. How to respond to a WebSocket open request with a subprotocol?

    In JavaScript a browser can specify a sub-protocol as the second parameter in a WebSocket creation:

    Experimenting with Chrome, this is correctly sent to the server as a Sec-WebSocket-Protocol element in the header.

    Using Django channels, a simple consumer

    gives the error

    WebSocket connection to ‘xxx’ failed: Error during WebSocket handshake: Sent non-empty ‘Sec-WebSocket-Protocol’ header but no response was received.

    What is the correct way to accept that connection request in Django channels’ ws_add function?

    3 Answers 3

    You have to specify the subprotocol to use in the websocket.accept message. For example, if you subclass channels.generic.websocket.WebsocketConsumer (also works with SyncConsumer ) and using a Sec-WebSocket-Protocol of my-protocol :

    I was having the same problem. The Websocket spec says that if a client asks for a subprotocol then the server must respond to let the client know it supports it. In my case the subprotocol was «graphql-ws»

    After digging around in the graphene code it eventually transpired that it is a simple case of adding the following to the settings:

    So, just replace the list of protocols with whatever you want to support. Of course once you’ve done this you actually need to then implement the subprotocol on the server.

    Server ( asyncio )#

    Start a WebSocket server listening on host and port .

    Whenever a client connects, the server creates a WebSocketServerProtocol , performs the opening handshake, and delegates to the connection handler, ws_handler .

    The handler receives the WebSocketServerProtocol and uses it to send and receive messages.

    Once the handler completes, either normally or with an exception, the server performs the closing handshake and closes the connection.

    Awaiting serve() yields a WebSocketServer . This object provides a close() method to shut down the server:

    serve() can be used as an asynchronous context manager. Then, the server is shut down automatically when exiting the context:

    port (Optional[int]) – TCP port the server listens on. See create_server() for details.

    create_protocol (Optional[Callable[. , WebSocketServerProtocol]]) – Factory for the asyncio.Protocol managing the connection. It defaults to WebSocketServerProtocol . Set it to a wrapper or a subclass to customize connection handling.

    logger (Optional[LoggerLike]) – Logger for this server. It defaults to logging.getLogger("websockets.server") . See the logging guide for details.

    compression (Optional[str]) – The “permessage-deflate” extension is enabled by default. Set compression to None to disable it. See the compression guide for details.

    origins (Optional[Sequence[Optional[Origin]]]) – Acceptable values of the Origin header, for defending against Cross-Site WebSocket Hijacking attacks. Include None in the list if the lack of an origin is acceptable.

    extensions (Optional[Sequence[ServerExtensionFactory]]) – List of supported extensions, in order in which they should be negotiated and run.

    subprotocols (Optional[Sequence[Subprotocol]]) – List of supported subprotocols, in order of decreasing preference.

    extra_headers (Union[HeadersLike, Callable[[str, Headers], HeadersLike]]) – Arbitrary HTTP headers to add to the response. This can be a HeadersLike or a callable taking the request path and headers in arguments and returning a HeadersLike .

    server_header (Optional[str]) – Value of the Server response header. It defaults to "Python/x.y.z websockets/X.Y" . Setting it to None removes the header.

    open_timeout (Optional[float]) – Timeout for opening connections in seconds. None disables the timeout.

    See WebSocketCommonProtocol for the documentation of ping_interval , ping_timeout , close_timeout , max_size , max_queue , read_limit , and write_limit .

    Any other keyword arguments are passed the event loop’s create_server() method.

    You can set ssl to a SSLContext to enable TLS.

    You can set sock to a socket that you created outside of websockets.

    await websockets.server. unix_serve ( ws_handler , path = None , * , create_protocol = None , logger = None , compression = ‘deflate’ , origins = None , extensions = None , subprotocols = None , extra_headers = None , server_header = ‘Python/x.y.z websockets/X.Y’ , process_request = None , select_subprotocol = None , ping_interval = 20 , ping_timeout = 20 , close_timeout = 10 , max_size = 2**20 , max_queue = 2**5 , read_limit = 2**16 , write_limit = 2**16 , ** kwds ) [source] #

    Start a WebSocket server listening on a Unix socket.

    This function is identical to serve() , except the host and port arguments are replaced by path . It is only available on Unix.

    Unrecognized keyword arguments are passed the event loop’s create_unix_server() method.

    It’s useful for deploying a server behind a reverse proxy such as nginx.

    path (str | None) – File system path to the Unix socket.

    Stopping a server#

    WebSocket server returned by serve() .

    This class provides the same interface as Server , notably the close() and wait_closed() methods.

    It keeps track of WebSocket connections in order to close them properly when shutting down.

    logger (Optional[LoggerLike]) – Logger for this server. It defaults to logging.getLogger("websockets.server") . See the logging guide for details.

    close ( close_connections = True ) [source] #

    Close the server.

    Close the underlying Server .

    When close_connections is True , which is the default, close existing connections. Specifically:

    Reject opening WebSocket connections with an HTTP 503 (service unavailable) error. This happens when the server accepted the TCP connection but didn’t complete the opening handshake before closing.

    Close open WebSocket connections with close code 1001 (going away).

    Wait until all connection handlers terminate.

    Wait until the server is closed.

    When wait_closed() returns, all TCP connections are closed and all connection handlers have returned.

    To ensure a fast shutdown, a connection handler should always be awaiting at least one of:

    recv() : when the connection is closed, it raises ConnectionClosedOK ;

    wait_closed() : when the connection is closed, it returns.

    Then the connection handler is immediately notified of the shutdown; it can clean up and exit.

    This is an alternative to using serve() as an asynchronous context manager. Shutdown is triggered by canceling serve_forever() instead of exiting a serve() context.

    Using a connection#

    WebSocket server connection.

    WebSocketServerProtocol provides recv() and send() coroutines for receiving and sending messages.

    It supports asynchronous iteration to receive messages:

    The iterator exits normally when the connection is closed with close code 1000 (OK) or 1001 (going away) or without a close code. It raises a ConnectionClosedError when the connection is closed with any other code.

    You may customize the opening handshake in a subclass by overriding process_request() or select_subprotocol() .

    ws_server (WebSocketServer) – WebSocket server that created this connection.

    See serve() for the documentation of ws_handler , logger , origins , extensions , subprotocols , extra_headers , and server_header .

    See WebSocketCommonProtocol for the documentation of ping_interval , ping_timeout , close_timeout , max_size , max_queue , read_limit , and write_limit .

    Receive the next message.

    When the connection is closed, recv() raises ConnectionClosed . Specifically, it raises ConnectionClosedOK after a normal connection closure and ConnectionClosedError after a protocol error or a network failure. This is how you detect the end of the message stream.

    Canceling recv() is safe. There’s no risk of losing the next message. The next invocation of recv() will return it.

    This makes it possible to enforce a timeout by wrapping recv() in timeout() or wait_for() .

    A string ( str ) for a Text frame. A bytestring ( bytes ) for a Binary frame.

    A string ( str ) is sent as a Text frame. A bytestring or bytes-like object ( bytes , bytearray , or memoryview ) is sent as a Binary frame.

    send() also accepts an iterable or an asynchronous iterable of strings, bytestrings, or bytes-like objects to enable fragmentation. Each item is treated as a message fragment and sent in its own frame. All items must be of the same type, or else send() will raise a TypeError and the connection will be closed.

    send() rejects dict-like objects because this is often an error. (If you want to send the keys of a dict-like object as fragments, call its keys() method and pass the result to send() .)

    Canceling send() is discouraged. Instead, you should close the connection with close() . Indeed, there are only two situations where send() may yield control to the event loop and then get canceled; in both cases, close() has the same effect and is more clear:

    The write buffer is full. If you don’t want to wait until enough data is sent, your only alternative is to close the connection. close() will likely time out then abort the TCP connection.

    message is an asynchronous iterator that yields control. Stopping in the middle of a fragmented message will cause a protocol error and the connection will be closed.

    When the connection is closed, send() raises ConnectionClosed . Specifically, it raises ConnectionClosedOK after a normal connection closure and ConnectionClosedError after a protocol error or a network failure.

    TypeError – If message doesn’t have a supported type.

    Perform the closing handshake.

    close() waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there’s no need to await wait_closed() after close() .

    close() is idempotent: it doesn’t do anything once the connection is closed.

    Wrapping close() in create_task() is safe, given that errors during connection termination aren’t particularly useful.

    Canceling close() is discouraged. If it takes too long, you can set a shorter close_timeout . If you don’t want to wait, let the Python process exit, then the OS will take care of closing the TCP connection.

    code (int) – WebSocket close code.

    reason (str) – WebSocket close reason.

    Wait until the connection is closed.

    This coroutine is identical to the closed attribute, except it can be awaited.

    This can make it easier to detect connection termination, regardless of its cause, in tasks that interact with the WebSocket connection.

    A ping may serve as a keepalive, as a check that the remote endpoint received all messages up to this point, or to measure latency .

    Canceling ping() is discouraged. If ping() doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.

    Canceling the Future returned by ping() has no effect.

    data (Optional[Data]) – payload of the ping; a string will be encoded to UTF-8; or None to generate a payload containing four random bytes.

    A future that will be completed when the corresponding pong is received. You can ignore it if you don’t intend to wait. The result of the future is the latency of the connection in seconds.

    RuntimeError – If another ping was sent with the same data and the corresponding pong wasn’t received yet.

    An unsolicited pong may serve as a unidirectional heartbeat.

    Canceling pong() is discouraged. If pong() doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.

    data (Data) – Payload of the pong. A string will be encoded to UTF-8.

    You can customize the opening handshake in a subclass by overriding these methods:

    await process_request ( path , request_headers ) [source] #

    Intercept the HTTP request and return an HTTP response if appropriate.

    You may override this method in a WebSocketServerProtocol subclass, for example:

    to return an HTTP 200 OK response on a given path; then a load balancer can use this path for a health check;

    to authenticate the request and return an HTTP 401 Unauthorized or an HTTP 403 Forbidden when authentication fails.

    You may also override this method with the process_request argument of serve() and WebSocketServerProtocol . This is equivalent, except process_request won’t have access to the protocol instance, so it can’t store information for later use.

    process_request() is expected to complete quickly. If it may run for a long time, then it should await wait_closed() and exit if wait_closed() completes, or else it could prevent the server from shutting down.

    path (str) – request path, including optional query string.

    request_headers (Headers) – request headers.

    None to continue the WebSocket handshake normally.

    An HTTP response, represented by a 3-uple of the response status, headers, and body, to abort the WebSocket handshake and return that HTTP response instead.

    select_subprotocol ( client_subprotocols , server_subprotocols ) [source] #

    Pick a subprotocol among those supported by the client and the server.

    If several subprotocols are available, select the preferred subprotocol by giving equal weight to the preferences of the client and the server.

    If no subprotocol is available, proceed without a subprotocol.

    You may provide a select_subprotocol argument to serve() or WebSocketServerProtocol to override this logic. For example, you could reject the handshake if the client doesn’t support a particular subprotocol, rather than accept the handshake without that subprotocol.

    client_subprotocols (Sequence[Subprotocol]) – list of subprotocols offered by the client.

    server_subprotocols (Sequence[Subprotocol]) – list of subprotocols available on the server.

    Selected subprotocol, if a common subprotocol was found.

    None to continue without a subprotocol.

    WebSocket connection objects also provide these attributes:

    Unique identifier of the connection. Useful in logs.

    Logger for this connection.

    Local address of the connection.

    For IPv4 connections, this is a (host, port) tuple.

    The format of the address depends on the address family; see getsockname() .

    None if the TCP connection isn’t established yet.

    Remote address of the connection.

    For IPv4 connections, this is a (host, port) tuple.

    The format of the address depends on the address family; see getpeername() .

    None if the TCP connection isn’t established yet.

    True when the connection is open; False otherwise.

    This attribute may be used to detect disconnections. However, this approach is discouraged per the EAFP principle. Instead, you should handle ConnectionClosed exceptions.

    True when the connection is closed; False otherwise.

    Be aware that both open and closed are False during the opening and closing sequences.

    Latency of the connection, in seconds.

    This value is updated after sending a ping frame and receiving a matching pong frame. Before the first ping, latency is 0 .

    By default, websockets enables a keepalive mechanism that sends ping frames automatically at regular intervals. You can also send ping frames and measure latency with ping() .

    The following attributes are available after the opening handshake, once the WebSocket connection is open:

    Path of the opening handshake request.

    Opening handshake request headers.

    Opening handshake response headers.

    Subprotocol, if one was negotiated.

    The following attributes are available after the closing handshake, once the WebSocket connection is closed:

    WebSocket close code, defined in section 7.1.5 of RFC 6455.

    None if the connection isn’t closed yet.

    WebSocket close reason, defined in section 7.1.6 of RFC 6455.

    None if the connection isn’t closed yet.

    Basic authentication#

    websockets supports HTTP Basic Authentication according to RFC 7235 and RFC 7617.

    websockets.auth. basic_auth_protocol_factory ( realm = None , credentials = None , check_credentials = None , create_protocol = None ) [source] #

    Protocol factory that enforces HTTP Basic Auth.

    basic_auth_protocol_factory() is designed to integrate with serve() like this:

    realm (str | None) – Scope of protection. It should contain only ASCII characters because the encoding of non-ASCII characters is undefined. Refer to section 2.2 of RFC 7235 for details.

    check_credentials (Callable[[str, str], Awaitable[bool]] | None) – Coroutine that verifies credentials. It receives username and password arguments and returns a bool . One of credentials or check_credentials must be provided but not both.

    TypeError – If the credentials or check_credentials argument is wrong.

    class websockets.auth. BasicAuthWebSocketServerProtocol ( * args , realm = None , check_credentials = None , ** kwargs ) [source] #

    WebSocket server protocol that enforces HTTP Basic Auth.

    Scope of protection.

    If provided, it should contain only ASCII characters because the encoding of non-ASCII characters is undefined.

    Username of the authenticated user.

    await check_credentials ( username , password ) [source] #

    Check whether credentials are authorized.

    This coroutine may be overridden in a subclass, for example to authenticate against a database or an external service.

    username (str) – HTTP Basic Auth username.

    password (str) – HTTP Basic Auth password.

    True if the handshake should continue; False if it should fail with an HTTP 401 error.

    Broadcast#

    Broadcast a message to several WebSocket connections.

    A string ( str ) is sent as a Text frame. A bytestring or bytes-like object ( bytes , bytearray , or memoryview ) is sent as a Binary frame.

    broadcast() pushes the message synchronously to all connections even if their write buffers are overflowing. There’s no backpressure.

    If you broadcast messages faster than a connection can handle them, messages will pile up in its write buffer until the connection times out. Keep ping_interval and ping_timeout low to prevent excessive memory usage from slow connections.

    Unlike send() , broadcast() doesn’t support sending fragmented messages. Indeed, fragmentation is useful for sending large messages without buffering them in memory, while broadcast() buffers one copy per connection as fast as possible.

    broadcast() skips connections that aren’t open in order to avoid errors on connections where the closing handshake is in progress.

    broadcast() ignores failures to write the message on some connections. It continues writing to other connections. On Python 3.11 and above, you may set raise_exceptions to True to record failures and raise all exceptions in a PEP 654 ExceptionGroup .

    websockets (Iterable[WebSocketCommonProtocol]) – WebSocket connections to which the message will be sent.

    message (str | bytes) – Message to send.

    raise_exceptions (bool) – Whether to raise an exception in case of failures.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *