# wsproto API

This document details the API of wsproto.

## Semantic Versioning

wsproto follows semantic versioning for its public API. Please note that the guarantees of semantic versioning apply only to the API that is documented here. Simply because a method or data field is not prefaced by an underscore does not make it part of wsproto’s public API. Anything not documented here is subject to change at any time.

## Connection

class `wsproto.``WSConnection`(connection_type: wsproto.connection.ConnectionType)

  Represents the local end of a WebSocket connection to a remote peer.

  `__init__`(connection_type: wsproto.connection.ConnectionType) → None

    Constructor

    Parameters: | connection_type (wsproto.connection.ConnectionType) – Controls whether the library behaves as a client or as a server.

  `events`() → Generator[wsproto.events.Event, None, None]

    A generator that yields pending events.

    Each event is an instance of a subclass of `wsproto.events.Event`.

  `receive_data`(data: Optional[bytes]) → None

    Feed network data into the connection instance.

    After calling this method, you should call `events()` to see if the received data triggered any new events.

    Parameters: | data (bytes) – Data received from remote peer

  `send`(event: wsproto.events.Event) → bytes

    Generate network data for the specified event.

    When you want to communicate with a WebSocket peer, you should construct an event and pass it to this method. This method will return the bytes that you should send to the peer.

    Parameters: | event (wsproto.events.Event) – The event to generate data for
    Returns bytes: | The data to send to the peer

  `state`

    Returns: | Connection state
    Return type: | wsproto.connection.ConnectionState

class `wsproto.``ConnectionType`

  An enumeration of connection types.

  `CLIENT` = 1

    This connection will act as client and talk to a remote server

  `SERVER` = 2

    This connection will as as server and waits for client connections

class `wsproto.connection.``ConnectionState`

  RFC 6455, Section 4 - Opening Handshake

  `CLOSED` = 4

    The closing handshake has completed.

  `CONNECTING` = 0

    The opening handshake is in progress.

  `LOCAL_CLOSING` = 3

    The local WebSocket (i.e. this instance) has initiated a connection close.

  `OPEN` = 1

    The opening handshake is complete.

  `REJECTING` = 5

    The connection was rejected during the opening handshake.

  `REMOTE_CLOSING` = 2

    The remote WebSocket has initiated a connection close.

## Handshake

class `wsproto.handshake.``H11Handshake`(connection_type: wsproto.connection.ConnectionType)

  A Handshake implementation for HTTP/1.1 connections.

  `connection`

    Return the established connection.

    This will either return the connection or raise a LocalProtocolError if the connection has not yet been established.

    Return type: | h11.Connection

  `events`() → Generator[wsproto.events.Event, None, None]

    Return a generator that provides any events that have been generated by protocol activity.

    Returns: | a generator that yields H11 events.

  `initiate_upgrade_connection`(headers: List[Tuple[bytes, bytes]], path: str) → None

    Initiate an upgrade connection.

    This should be used if the request has already be received and parsed.

    Parameters:

    - headers (list) – HTTP headers represented as a list of 2-tuples.
    - path (str) – A URL path.

  `receive_data`(data: Optional[bytes]) → None

    Receive data from the remote.

    A list of events that the remote peer triggered by sending this data can be retrieved with `events()`.

    Parameters: | data (bytes) – Data received from the WebSocket peer.

  `send`(event: wsproto.events.Event) → bytes

    Send an event to the remote.

    This will return the bytes to send based on the event or raise a LocalProtocolError if the event is not valid given the state.

    Returns: | Data to send to the WebSocket peer.
    Return type: | bytes

`wsproto.handshake.``client_extensions_handshake`(accepted: List[str], supported: List[wsproto.extensions.Extension]) → List[wsproto.extensions.Extension]

`wsproto.handshake.``server_extensions_handshake`(requested: List[str], supported: List[wsproto.extensions.Extension]) → Optional[bytes]

  Agree on the extensions to use returning an appropriate header value.

  This returns None if there are no agreed extensions

## Events

Event constructors accept any field as a keyword argument. Some fields are required, while others have default values.

class `wsproto.events.``Event`

  Base class for wsproto events.

class `wsproto.events.``Request`(host: str, target: str, extensions: Union[Sequence[wsproto.extensions.Extension], Sequence[str]] = <factory>, extra_headers: List[Tuple[bytes, bytes]] = <factory>, subprotocols: List[str] = <factory>)

  The beginning of a Websocket connection, the HTTP Upgrade request

  This event is fired when a SERVER connection receives a WebSocket handshake request (HTTP with upgrade header).

  Fields:

  `host`

    (Required) The hostname, or host header value.

  `target`

    (Required) The request target (path and query string)

  `extensions`

    The proposed extensions.

  `extra_headers`

    The additional request headers, excluding extensions, host, subprotocols, and version headers.

  `subprotocols`

    A list of the subprotocols proposed in the request, as a list of strings.

class `wsproto.events.``AcceptConnection`(subprotocol: Optional[str] = None, extensions: List[wsproto.extensions.Extension] = <factory>, extra_headers: List[Tuple[bytes, bytes]] = <factory>)

  The acceptance of a Websocket upgrade request.

  This event is fired when a CLIENT receives an acceptance response from a server. It is also used to accept an upgrade request when acting as a SERVER.

  Fields:

  `extra_headers`

    Any additional (non websocket related) headers present in the acceptance response.

  `subprotocol`

    The accepted subprotocol to use.

class `wsproto.events.``RejectConnection`(status_code: int = 400, headers: List[Tuple[bytes, bytes]] = <factory>, has_body: bool = False)

  The rejection of a Websocket upgrade request, the HTTP response.

  The `RejectConnection` event sends the appropriate HTTP headers to communicate to the peer that the handshake has been rejected. You may also send an HTTP body by setting the `has_body` attribute to `True` and then sending one or more `RejectData` events after this one. When sending a response body, the caller should set the `Content-Length`, `Content-Type`, and/or `Transfer-Encoding` headers as appropriate.

  When receiving a `RejectConnection` event, the `has_body` attribute will in almost all cases be `True` (even if the server set it to `False`) and will be followed by at least one `RejectData` events, even though the data itself might be just `b""`. (The only scenario in which the caller receives a `RejectConnection` with `has_body == False` is if the peer violates sends an informational status code (1xx) other than 101.)

  The `has_body` attribute should only be used when receiving the event. (It has ) is False the headers must include a content-length or transfer encoding.

  Fields:

  `headers`(Headers)

    The headers to send with the response.

  `has_body`

    This defaults to False, but set to True if there is a body. See also `RejectData`.

  `status_code`

    The response status code.

class `wsproto.events.``RejectData`(data: bytes, body_finished: bool = True)

  The rejection HTTP response body.

  The caller may send multiple `RejectData` events. The final event should have the `body_finished` attribute set to `True`.

  Fields:

  `body_finished`

    True if this is the final chunk of the body data.

  `data`(bytes)

    (Required) The raw body data.

class `wsproto.events.``CloseConnection`(code: int, reason: Optional[str] = None)

  The end of a Websocket connection, represents a closure frame.

  wsproto does not automatically send a response to a close event. To comply with the RFC you MUST send a close event back to the remote WebSocket if you have not already sent one. The `response()` method provides a suitable event for this purpose, and you should check if a response needs to be sent by checking `wsproto.WSConnection.state()`.

  Fields:

  `code`

    (Required) The integer close code to indicate why the connection has closed.

  `reason`

    Additional reasoning for why the connection has closed.

  `response`() → wsproto.events.CloseConnection

    Generate an RFC-compliant close frame to send back to the peer.

class `wsproto.events.``Message`(data: T, frame_finished: bool = True, message_finished: bool = True)

  The websocket data message.

  Fields:

  `data`

    (Required) The message data as byte string, can be decoded as UTF-8 for TEXT messages. This only represents a single chunk of data and not a full WebSocket message. You need to buffer and reassemble these chunks to get the full message.

  `frame_finished`

    This has no semantic content, but is provided just in case some weird edge case user wants to be able to reconstruct the fragmentation pattern of the original stream.

  `message_finished`

    True if this frame is the last one of this message, False if more frames are expected.

class `wsproto.events.``TextMessage`(data: str, frame_finished: bool = True, message_finished: bool = True)

  This event is fired when a data frame with TEXT payload is received.

  Fields:

  `data`

    The message data as string, This only represents a single chunk of data and not a full WebSocket message. You need to buffer and reassemble these chunks to get the full message.

class `wsproto.events.``BytesMessage`(data: bytes, frame_finished: bool = True, message_finished: bool = True)

  This event is fired when a data frame with BINARY payload is received.

  Fields:

  `data`

    The message data as byte string, can be decoded as UTF-8 for TEXT messages. This only represents a single chunk of data and not a full WebSocket message. You need to buffer and reassemble these chunks to get the full message.

class `wsproto.events.``Ping`(payload: bytes = b'')

  The Ping event can be sent to trigger a ping frame and is fired when a Ping is received.

  wsproto does not automatically send a pong response to a ping event. To comply with the RFC you MUST send a pong even as soon as is practical. The `response()` method provides a suitable event for this purpose.

  Fields:

  `payload`

    An optional payload to emit with the ping frame.

  `response`() → wsproto.events.Pong

    Generate an RFC-compliant `Pong` response to this ping.

class `wsproto.events.``Pong`(payload: bytes = b'')

  The Pong event is fired when a Pong is received.

  Fields:

  `payload`

    An optional payload to emit with the pong frame.

## Frame Protocol

class `wsproto.frame_protocol.``Opcode`

  RFC 6455, Section 5.2 - Base Framing Protocol

  `BINARY` = 2

    Binary message

  `CLOSE` = 8

    Close frame

  `CONTINUATION` = 0

    Contiuation frame

  `PING` = 9

    Ping frame

  `PONG` = 10

    Pong frame

  `TEXT` = 1

    Text message

class `wsproto.frame_protocol.``CloseReason`

  RFC 6455, Section 7.4.1 - Defined Status Codes

  `ABNORMAL_CLOSURE` = 1006

    is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint. It is designated for use in applications expecting a status code to indicate that the connection was closed abnormally, e.g., without sending or receiving a Close control frame.

  `GOING_AWAY` = 1001

    indicates that an endpoint is “going away”, such as a server going down or a browser having navigated away from a page.

  `INTERNAL_ERROR` = 1011

    indicates that a server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.

  `INVALID_FRAME_PAYLOAD_DATA` = 1007

    indicates that an endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [RFC3629] data within a text message).

  `MANDATORY_EXT` = 1010

    indicates that an endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn’t return them in the response message of the WebSocket handshake. The list of extensions that are needed SHOULD appear in the /reason/ part of the Close frame. Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.

  `MESSAGE_TOO_BIG` = 1009

    indicates that an endpoint is terminating the connection because it has received a message that is too big for it to process.

  `NORMAL_CLOSURE` = 1000

    indicates a normal closure, meaning that the purpose for which the connection was established has been fulfilled.

  `NO_STATUS_RCVD` = 1005

    is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint. It is designated for use in applications expecting a status code to indicate that no status code was actually present.

  `POLICY_VIOLATION` = 1008

    indicates that an endpoint is terminating the connection because it has received a message that violates its policy. This is a generic status code that can be returned when there is no other more suitable status code (e.g., 1003 or 1009) or if there is a need to hide specific details about the policy.

  `PROTOCOL_ERROR` = 1002

    indicates that an endpoint is terminating the connection due to a protocol error.

  `SERVICE_RESTART` = 1012

    Server/service is restarting (not part of RFC6455)

  `TLS_HANDSHAKE_FAILED` = 1015

    is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint. It is designated for use in applications expecting a status code to indicate that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can’t be verified).

  `TRY_AGAIN_LATER` = 1013

    Temporary server condition forced blocking client’s request (not part of RFC6455)

  `UNSUPPORTED_DATA` = 1003

    indicates that an endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).

## Extensions

class `wsproto.extensions.``Extension`

`wsproto.extensions.``SUPPORTED_EXTENSIONS` = {'permessage-deflate': <class 'wsproto.extensions.PerMessageDeflate'>}

  SUPPORTED_EXTENSIONS maps all supported extension names to their class. This can be used to iterate all supported extensions of wsproto, instantiate new extensions based on their name, or check if a given extension is supported or not.

## Exceptions

class `wsproto.utilities.``LocalProtocolError`

  Indicates an error due to local/programming errors.

  This is raised when the connection is asked to do something that is either incompatible with the state or the websocket standard.

class `wsproto.utilities.``RemoteProtocolError`(message: str, event_hint: Optional[wsproto.events.Event] = None)

  Indicates an error due to the remote’s actions.

  This is raised when processing the bytes from the remote if the remote has sent data that is incompatible with the websocket standard.

  `event_hint`

    This is a suggested wsproto Event to send to the client based on the error. It could be None if no hint is available.