Utilities#

Broadcast#

websockets.broadcast(websockets, message)[source]#

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.

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

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 low values for ping_interval and ping_timeout to prevent excessive memory usage by slow connections when you use broadcast().

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.

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

  • message (Data) – message to send.

Raises
  • RuntimeError – if a connection is busy sending a fragmented message.

  • TypeError – if message doesn’t have a supported type.

WebSocket events#

class websockets.frames.Frame(opcode, data, fin=True, rsv1=False, rsv2=False, rsv3=False)[source]#

WebSocket frame.

opcode#

Opcode.

Type

websockets.frames.Opcode

data#

Payload data.

Type

bytes

fin#

FIN bit.

Type

bool

rsv1#

RSV1 bit.

Type

bool

rsv2#

RSV2 bit.

Type

bool

rsv3#

RSV3 bit.

Type

bool

Only these fields are needed. The MASK bit, payload length and masking-key are handled on the fly when parsing and serializing frames.

class websockets.frames.Opcode(value)[source]#

Opcode values for WebSocket frames.

CONT = 0#
TEXT = 1#
BINARY = 2#
CLOSE = 8#
PING = 9#
PONG = 10#
class websockets.frames.Close(code, reason)[source]#

Code and reason for WebSocket close frames.

code#

Close code.

Type

int

reason#

Close reason.

Type

str

HTTP events#

class websockets.http11.Request(path, headers, exception=None)[source]#

WebSocket handshake request.

path#

Request path, including optional query.

Type

str

headers#

Request headers.

Type

websockets.datastructures.Headers

exception#

If processing the response triggers an exception, the exception is stored in this attribute.

Type

Optional[Exception]

class websockets.http11.Response(status_code, reason_phrase, headers, body=None, exception=None)[source]#

WebSocket handshake response.

status_code#

Response code.

Type

int

reason_phrase#

Response reason.

Type

str

headers#

Response headers.

Type

websockets.datastructures.Headers

body#

Response body, if any.

Type

Optional[bytes]

exception#

if processing the response triggers an exception, the exception is stored in this attribute.

Type

Optional[Exception]

class websockets.datastructures.Headers(*args, **kwargs)[source]#

Efficient data structure for manipulating HTTP headers.

A list of (name, values) is inefficient for lookups.

A dict doesn’t suffice because header names are case-insensitive and multiple occurrences of headers with the same name are possible.

Headers stores HTTP headers in a hybrid data structure to provide efficient insertions and lookups while preserving the original data.

In order to account for multiple values with minimal hassle, Headers follows this logic:

  • When getting a header with headers[name]:
    • if there’s no value, KeyError is raised;

    • if there’s exactly one value, it’s returned;

    • if there’s more than one value, MultipleValuesError is raised.

  • When setting a header with headers[name] = value, the value is appended to the list of values for that header.

  • When deleting a header with del headers[name], all values for that header are removed (this is slow).

Other methods for manipulating headers are consistent with this logic.

As long as no header occurs multiple times, Headers behaves like dict, except keys are lower-cased to provide case-insensitivity.

Two methods support manipulating multiple values explicitly:

  • get_all() returns a list of all values for a header;

  • raw_items() returns an iterator of (name, values) pairs.

get_all(key)[source]#

Return the (possibly empty) list of all values for a header.

Parameters

key (str) – header name.

raw_items()[source]#

Return an iterator of all values as (name, value) pairs.

exception websockets.datastructures.MultipleValuesError[source]#

Exception raised when Headers has more than one value for a key.

URIs#

websockets.uri.parse_uri(uri)[source]#

Parse and validate a WebSocket URI.

Parameters

uri (str) – WebSocket URI.

Returns

Parsed WebSocket URI.

Return type

WebSocketURI

Raises

InvalidURI – if uri isn’t a valid WebSocket URI.

class websockets.uri.WebSocketURI(secure, host, port, path, query, username, password)[source]#

WebSocket URI.

secure#

True for a wss URI, False for a ws URI.

Type

bool

host#

Normalized to lower case.

Type

str

port#

Always set even if it’s the default.

Type

int

path#

May be empty.

Type

str

query#

May be empty if the URI doesn’t include a query component.

Type

str

username#

Available when the URI contains User Information.

Type

Optional[str]

password#

Available when the URI contains User Information.

Type

Optional[str]