Module autobahn.websocket

WebSocket Interfaces

class autobahn.websocket.interfaces.IWebSocketChannel[source]

A WebSocket channel is a bidirectional, full-duplex, ordered, reliable message channel over a WebSocket connection as specified in RFC6455.

This interface defines a message-based API to WebSocket plus auxiliary hooks and methods.

When a WebSocket connection is established, the following callbacks are fired:

Once a WebSocket connection is open, messages can be sent and received using:

The WebSocket connection can be closed and closing observed using:

Finally, WebSocket ping/pong messages (e.g. for heart-beating) can use:

abstract onClose(wasClean: bool, code: int, reason: str)[source]

Callback fired when the WebSocket connection has been closed (WebSocket closing handshake has been finished or the connection was closed uncleanly).

Parameters
  • wasCleanTrue iff the WebSocket connection was closed cleanly.

  • code – Close status code as sent by the WebSocket peer.

  • reason – Close reason as sent by the WebSocket peer.

abstract onConnect(request_or_response: Union[ConnectionRequest, ConnectionResponse]) Union[str, None, Tuple[Optional[str], Dict[str, str]]][source]

Callback fired during WebSocket opening handshake when a client connects to a server with request with a ConnectionRequest from the client or when a server connection was established by a client with a ConnectionResponse response from the server.

This method may run asynchronously.

Parameters

request_or_response (Instance of autobahn.websocket.types.ConnectionRequest or autobahn.websocket.types.ConnectionResponse.) – Connection request (for servers) or response (for clients).

Returns

When this callback is fired on a WebSocket server, you may return one of:
  • None: the connection is accepted with no specific WebSocket subprotocol,

  • str: the connection is accepted with the returned name as the WebSocket subprotocol, or

  • (str, dict): a pair of subprotocol accepted and HTTP headers to send to the client.

When this callback is fired on a WebSocket client, this method must return None. To deny a connection (client and server), raise an Exception. You can also return a Deferred/Future that resolves/rejects to the above.

abstract onConnecting(transport_details: TransportDetails) Optional[ConnectingRequest][source]

This method is called when the WebSocket peer is connected at the byte stream level (e.g. TCP, TLS or Serial), but before the WebSocket opening handshake (e.g. at the HTTP request level).

Parameters

transport_details – information about the transport.

Returns

A autobahn.websocket.types.ConnectingRequest instance is returned to indicate which options should be used for this connection. If you wish to use the default behavior, None may be returned (this is the default).

abstract onMessage(payload: bytes, isBinary: bool)[source]

Callback fired when a complete WebSocket message was received.

This method may run asynchronously.

Parameters
  • payload – The WebSocket message received.

  • isBinary – Flag indicating whether payload is binary or UTF-8 encoded text.

abstract onOpen()[source]

Callback fired when the initial WebSocket opening handshake was completed. You now can send and receive WebSocket messages.

This method may run asynchronously.

abstract onPing(payload: bytes)[source]

Callback fired when a WebSocket ping was received. A default implementation responds by sending a WebSocket pong.

Parameters

payload – Payload of ping (when there was any). Can be arbitrary, up to 125 octets.

abstract onPong(payload: bytes)[source]

Callback fired when a WebSocket pong was received. A default implementation does nothing.

Parameters

payload – Payload of pong (when there was any). Can be arbitrary, up to 125 octets.

abstract sendClose(code: Optional[int] = None, reason: Optional[str] = None)[source]

Starts a WebSocket closing handshake tearing down the WebSocket connection.

Parameters
  • code – An optional close status code (1000 for normal close or 3000-4999 for application specific close).

  • reason – An optional close reason (a string that when present, a status code MUST also be present).

abstract sendMessage(payload: bytes, isBinary: bool)[source]

Send a WebSocket message over the connection to the peer.

Parameters
  • payload – The WebSocket message to be sent.

  • isBinary – Flag indicating whether payload is binary or UTF-8 encoded text.

abstract sendPing(payload: Optional[bytes] = None)[source]

Send a WebSocket ping to the peer.

A peer is expected to pong back the payload a soon as “practical”. When more than one ping is outstanding at a peer, the peer may elect to respond only to the last ping.

Parameters

payload – An (optional) arbitrary payload of length less than 126 octets.

abstract sendPong(payload: Optional[bytes] = None)[source]

Send a WebSocket pong to the peer.

A WebSocket pong may be sent unsolicited. This serves as a unidirectional heartbeat. A response to an unsolicited pong is “not expected”.

Parameters

payload – An (optional) arbitrary payload of length < 126 octets.

class autobahn.websocket.interfaces.IWebSocketServerChannelFactory(url=None, protocols=None, server=None, headers=None, externalPort=None)[source]

WebSocket server protocol factories implement this interface, and create protocol instances which in turn implement autobahn.websocket.interfaces.IWebSocketChannel.

Parameters
  • url (str) – The WebSocket URL this factory is working for, e.g. ws://myhost.com/somepath. For non-TCP transports like pipes or Unix domain sockets, provide None. This will use an implicit URL of ws://localhost.

  • protocols (list of str) – List of subprotocols the server supports. The subprotocol used is the first from the list of subprotocols announced by the client that is contained in this list.

  • server (str) – Server as announced in HTTP response header during opening handshake.

  • headers (dict) – An optional mapping of additional HTTP headers to send during the WebSocket opening handshake.

  • externalPort (int) – Optionally, the external visible port this server will be reachable under (i.e. when running behind a L2/L3 forwarding device).

abstract resetProtocolOptions()[source]

Reset all WebSocket protocol options to defaults.

abstract setProtocolOptions(versions=None, webStatus=None, utf8validateIncoming=None, maskServerFrames=None, requireMaskedClientFrames=None, applyMask=None, maxFramePayloadSize=None, maxMessagePayloadSize=None, autoFragmentSize=None, failByDrop=None, echoCloseCodeReason=None, openHandshakeTimeout=None, closeHandshakeTimeout=None, tcpNoDelay=None, perMessageCompressionAccept=None, autoPingInterval=None, autoPingTimeout=None, autoPingSize=None, serveFlashSocketPolicy=None, flashSocketPolicy=None, allowedOrigins=None, allowNullOrigin=False, maxConnections=None, trustXForwardedFor=0)[source]

Set WebSocket protocol options used as defaults for new protocol instances.

Parameters
  • versions (list of ints or None) – The WebSocket protocol versions accepted by the server (default: autobahn.websocket.protocol.WebSocketProtocol.SUPPORTED_PROTOCOL_VERSIONS()).

  • webStatus (bool or None) – Return server status/version on HTTP/GET without WebSocket upgrade header (default: True).

  • utf8validateIncoming (bool or None) – Validate incoming UTF-8 in text message payloads (default: True).

  • maskServerFrames (bool or None) – Mask server-to-client frames (default: False).

  • requireMaskedClientFrames (bool or None) – Require client-to-server frames to be masked (default: True).

  • applyMask (bool or None) – Actually apply mask to payload when mask it present. Applies for outgoing and incoming frames (default: True).

  • maxFramePayloadSize (int or None) – Maximum frame payload size that will be accepted when receiving or 0 for unlimited (default: 0).

  • maxMessagePayloadSize (int or None) – Maximum message payload size (after reassembly of fragmented messages) that will be accepted when receiving or 0 for unlimited (default: 0).

  • autoFragmentSize (int or None) – Automatic fragmentation of outgoing data messages (when using the message-based API) into frames with payload length <= this size or 0 for no auto-fragmentation (default: 0).

  • failByDrop (bool or None) – Fail connections by dropping the TCP connection without performing closing handshake (default: True).

  • echoCloseCodeReason (bool or None) – Iff true, when receiving a close, echo back close code/reason. Otherwise reply with code == 1000, reason = “” (default: False).

  • openHandshakeTimeout (float or None) – Opening WebSocket handshake timeout, timeout in seconds or 0 to deactivate (default: 0).

  • closeHandshakeTimeout (float or None) – When we expect to receive a closing handshake reply, timeout in seconds (default: 1).

  • tcpNoDelay (bool or None) – TCP NODELAY (“Nagle”) socket option (default: True).

  • perMessageCompressionAccept (callable or None) – Acceptor function for offers.

  • autoPingInterval (float or None) – Automatically send WebSocket pings every given seconds. When the peer does not respond in autoPingTimeout, drop the connection. Set to 0 to disable. (default: 0).

  • autoPingTimeout (float or None) – Wait this many seconds for the peer to respond to automatically sent pings. If the peer does not respond in time, drop the connection. Set to 0 to disable. (default: 0).

  • autoPingSize (int or None) – Payload size for automatic pings/pongs. Must be an integer from [12, 125]. (default: 12).

  • serveFlashSocketPolicy (bool or None) – Serve the Flash Socket Policy when we receive a policy file request on this protocol. (default: False).

  • flashSocketPolicy (str or None) –

    The flash socket policy to be served when we are serving

    the Flash Socket Policy on this protocol

    and when Flash tried to connect to the destination port. It must end with a null character.

  • allowedOrigins (list or None) – A list of allowed WebSocket origins (with ‘*’ as a wildcard character).

  • allowNullOrigin (bool) – if True, allow WebSocket connections whose Origin: is “null”.

  • maxConnections (int or None) – Maximum number of concurrent connections. Set to 0 to disable (default: 0).

  • trustXForwardedFor (int) – Number of trusted web servers in front of this server that add their own X-Forwarded-For header (default: 0)

abstract setSessionParameters(url=None, protocols=None, server=None, headers=None, externalPort=None)[source]

Set WebSocket session parameters.

Parameters
  • url (str) – The WebSocket URL this factory is working for, e.g. ws://myhost.com/somepath. For non-TCP transports like pipes or Unix domain sockets, provide None. This will use an implicit URL of ws://localhost.

  • protocols (list of str) – List of subprotocols the server supports. The subprotocol used is the first from the list of subprotocols announced by the client that is contained in this list.

  • server (str) – Server as announced in HTTP response header during opening handshake.

  • headers (dict) – An optional mapping of additional HTTP headers to send during the WebSocket opening handshake.

  • externalPort (int) – Optionally, the external visible port this server will be reachable under (i.e. when running behind a L2/L3 forwarding device).

class autobahn.websocket.interfaces.IWebSocketClientChannelFactory(url=None, origin=None, protocols=None, useragent=None, headers=None, proxy=None)[source]

WebSocket client protocol factories implement this interface, and create protocol instances which in turn implement autobahn.websocket.interfaces.IWebSocketChannel.

Note that you MUST provide URL either here or set using autobahn.websocket.WebSocketClientFactory.setSessionParameters() before the factory is started.

Parameters
  • url (str) – WebSocket URL this factory will connect to, e.g. ws://myhost.com/somepath?param1=23. For non-TCP transports like pipes or Unix domain sockets, provide None. This will use an implicit URL of ws://localhost.

  • origin (str) – The origin to be sent in WebSocket opening handshake or None (default: None).

  • protocols (list of strings) – List of subprotocols the client should announce in WebSocket opening handshake (default: []).

  • useragent (str) – User agent as announced in HTTP request header or None (default: AutobahnWebSocket/?.?.?).

  • headers (dict) – An optional mapping of additional HTTP headers to send during the WebSocket opening handshake.

  • proxy (dict or None) – Explicit proxy server to use; a dict with host and port keys

abstract resetProtocolOptions()[source]

Reset all WebSocket protocol options to defaults.

abstract setProtocolOptions(version=None, utf8validateIncoming=None, acceptMaskedServerFrames=None, maskClientFrames=None, applyMask=None, maxFramePayloadSize=None, maxMessagePayloadSize=None, autoFragmentSize=None, failByDrop=None, echoCloseCodeReason=None, serverConnectionDropTimeout=None, openHandshakeTimeout=None, closeHandshakeTimeout=None, tcpNoDelay=None, perMessageCompressionOffers=None, perMessageCompressionAccept=None, autoPingInterval=None, autoPingTimeout=None, autoPingSize=None)[source]

Set WebSocket protocol options used as defaults for _new_ protocol instances.

Parameters
  • version (int) – The WebSocket protocol spec (draft) version to be used (default: autobahn.websocket.protocol.WebSocketProtocol.SUPPORTED_PROTOCOL_VERSIONS()).

  • utf8validateIncoming (bool) – Validate incoming UTF-8 in text message payloads (default: True).

  • acceptMaskedServerFrames (bool) – Accept masked server-to-client frames (default: False).

  • maskClientFrames (bool) – Mask client-to-server frames (default: True).

  • applyMask (bool) – Actually apply mask to payload when mask it present. Applies for outgoing and incoming frames (default: True).

  • maxFramePayloadSize (int) – Maximum frame payload size that will be accepted when receiving or 0 for unlimited (default: 0).

  • maxMessagePayloadSize (int) – Maximum message payload size (after reassembly of fragmented messages) that will be accepted when receiving or 0 for unlimited (default: 0).

  • autoFragmentSize (int) – Automatic fragmentation of outgoing data messages (when using the message-based API) into frames with payload length <= this size or 0 for no auto-fragmentation (default: 0).

  • failByDrop (bool) – Fail connections by dropping the TCP connection without performing closing handshake (default: True).

  • echoCloseCodeReason (bool) – Iff true, when receiving a close, echo back close code/reason. Otherwise reply with code == 1000, reason = “” (default: False).

  • serverConnectionDropTimeout (float) – When the client expects the server to drop the TCP, timeout in seconds (default: 1).

  • openHandshakeTimeout (float) – Opening WebSocket handshake timeout, timeout in seconds or 0 to deactivate (default: 0).

  • closeHandshakeTimeout (float) – When we expect to receive a closing handshake reply, timeout in seconds (default: 1).

  • tcpNoDelay (bool) – TCP NODELAY (“Nagle”): bool socket option (default: True).

  • perMessageCompressionOffers (list of instance of subclass of PerMessageCompressOffer) – A list of offers to provide to the server for the permessage-compress WebSocket extension. Must be a list of instances of subclass of PerMessageCompressOffer.

  • perMessageCompressionAccept (callable) – Acceptor function for responses.

  • autoPingInterval (float or None) – Automatically send WebSocket pings every given seconds. When the peer does not respond in autoPingTimeout, drop the connection. Set to 0 to disable. (default: 0).

  • autoPingTimeout (float or None) – Wait this many seconds for the peer to respond to automatically sent pings. If the peer does not respond in time, drop the connection. Set to 0 to disable. (default: 0).

  • autoPingSize (int) – Payload size for automatic pings/pongs. Must be an integer from [12, 125]. (default: 12).

abstract setSessionParameters(url=None, origin=None, protocols=None, useragent=None, headers=None, proxy=None)[source]

Set WebSocket session parameters.

Parameters
  • url (str) – WebSocket URL this factory will connect to, e.g. ws://myhost.com/somepath?param1=23. For non-TCP transports like pipes or Unix domain sockets, provide None. This will use an implicit URL of ws://localhost.

  • origin (str) – The origin to be sent in opening handshake.

  • protocols (list of strings) – List of WebSocket subprotocols the client should announce in opening handshake.

  • useragent (str) – User agent as announced in HTTP request header during opening handshake.

  • headers (dict) – An optional mapping of additional HTTP headers to send during the WebSocket opening handshake.

  • proxy (dict or None) – (Optional) a dict with host and port keys specifying a proxy to use

WebSocket Types

class autobahn.websocket.types.ConnectingRequest(host=None, port=None, resource=None, headers=None, useragent=None, origin=None, protocols=None)[source]

Thin-wrapper for WebSocket connection request information provided in autobahn.websocket.protocol.WebSocketClientProtocol.onConnecting() after a client has connected, but before the handshake has proceeded.

host, port, and resource are all required, everything else is optional. Note that these are values that will be seen by the client and should represent the public-facing host, port and resource to which the client is connecting (not necessarily the action host/port being used).

Any of the arguments can be None, which will provide a useful default.

Parameters
  • host (str) – the host to present to the server

  • port (int) – the port to present to the server

  • resouce (str) –

  • headers (dict) – extra HTTP headers to send in the opening handshake

class autobahn.websocket.types.ConnectionAccept(subprotocol=None, headers=None)[source]

Used by WebSocket servers to accept an incoming WebSocket connection. If the client announced one or multiple subprotocols, the server MUST select one of the subprotocols announced by the client.

Parameters
  • subprotocol (unicode or None) – The WebSocket connection is accepted with the this WebSocket subprotocol chosen. The value must be a token as defined by RFC 2616.

  • headers (dict or None) – Additional HTTP headers to send on the WebSocket opening handshake reply, e.g. cookies. The keys must be unicode, and the values either unicode or tuple/list. In the latter case a separate HTTP header line will be sent for each item in tuple/list.

exception autobahn.websocket.types.ConnectionDeny(code, reason=None)[source]

Throw an instance of this class to deny a WebSocket connection during handshake in autobahn.websocket.protocol.WebSocketServerProtocol.onConnect().

Parameters
  • code (int) – HTTP error code.

  • reason (unicode) – HTTP error reason.

BAD_REQUEST = 400

Bad Request. The request cannot be fulfilled due to bad syntax.

FORBIDDEN = 403

Forbidden. The request was a legal request, but the server is refusing to respond to it.[2] Unlike a 401 Unauthorized response, authenticating will make no difference.

INTERNAL_SERVER_ERROR = 500

Internal Server Error. A generic error message, given when no more specific message is suitable.

NOT_ACCEPTABLE = 406

Not Acceptable. The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.

NOT_FOUND = 404

Not Found. The requested resource could not be found but may be available again in the future.[2] Subsequent requests by the client are permissible.

NOT_IMPLEMENTED = 501

Not Implemented. The server either does not recognize the request method, or it lacks the ability to fulfill the request.

REQUEST_TIMEOUT = 408

Request Timeout. The server timed out waiting for the request. According to W3 HTTP specifications: ‘The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

SERVICE_UNAVAILABLE = 503

Service Unavailable. The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.

class autobahn.websocket.types.ConnectionRequest(peer, headers, host, path, params, version, origin, protocols, extensions)[source]

Thin-wrapper for WebSocket connection request information provided in autobahn.websocket.protocol.WebSocketServerProtocol.onConnect() when a WebSocket client want to establish a connection to a WebSocket server.

Parameters
  • peer (str) – Descriptor of the connecting client (e.g. IP address/port in case of TCP transports).

  • headers (dict) – HTTP headers from opening handshake request.

  • host (str) – Host from opening handshake HTTP header.

  • path (str) – Path from requested HTTP resource URI. For example, a resource URI of /myservice?foo=23&foo=66&bar=2 will be parsed to /myservice.

  • params (dict) – Query parameters (if any) from requested HTTP resource URI. For example, a resource URI of /myservice?foo=23&foo=66&bar=2 will be parsed to {'foo': ['23', '66'], 'bar': ['2']}.

  • version (int) – The WebSocket protocol version the client announced (and will be spoken, when connection is accepted).

  • origin (str) – The WebSocket origin header or None. Note that this only a reliable source of information for browser clients!

  • protocols (list) – The WebSocket (sub)protocols the client announced. You must select and return one of those (or None) in autobahn.websocket.WebSocketServerProtocol.onConnect().

  • extensions (list) – The WebSocket extensions the client requested and the server accepted, and thus will be spoken, once the WebSocket connection has been fully established.

class autobahn.websocket.types.ConnectionResponse(peer, headers, version, protocol, extensions)[source]

Thin-wrapper for WebSocket connection response information provided in autobahn.websocket.protocol.WebSocketClientProtocol.onConnect() when a WebSocket server has accepted a connection request by a client.

Constructor.

Parameters
  • peer (str) – Descriptor of the connected server (e.g. IP address/port in case of TCP transport).

  • headers (dict) – HTTP headers from opening handshake response.

  • version (int) – The WebSocket protocol version that is spoken.

  • protocol (str) – The WebSocket (sub)protocol in use.

  • extensions (list of str) – The WebSocket extensions in use.

class autobahn.websocket.types.IncomingMessage(payload, is_binary=False)[source]

An incoming WebSocket message.

Parameters
  • payload (bytes) – The WebSocket message payload, which can be UTF-8 encoded text or a binary string.

  • is_binary (bool) – True for binary payload, else the payload contains UTF-8 encoded text.

class autobahn.websocket.types.Message[source]

Abstract base class for WebSocket messages.

class autobahn.websocket.types.OutgoingMessage(payload, is_binary=False, skip_compress=False)[source]

An outgoing WebSocket message.

Parameters
  • payload (bytes) – The WebSocket message payload, which can be UTF-8 encoded text or a binary string.

  • is_binary (bool) – True iff payload is binary, else the payload contains UTF-8 encoded text.

  • skip_compress (bool) – If True, never compress this message. This only has an effect when WebSocket compression has been negotiated on the WebSocket connection. Use when you know the payload is incompressible (e.g. encrypted or already compressed).

class autobahn.websocket.types.Ping(payload=None)[source]

A WebSocket ping message.

Parameters

payload (bytes or None) – The WebSocket ping message payload.

WebSocket Compression

class autobahn.websocket.compress.PerMessageBzip2(is_server, server_max_compress_level, client_max_compress_level)[source]

permessage-bzip2 WebSocket extension processor.

class autobahn.websocket.compress.PerMessageBzip2Offer(accept_max_compress_level=True, request_max_compress_level=0)[source]

Set of extension parameters for permessage-bzip2 WebSocket extension offered by a client to a server.

Constructor.

Parameters
  • accept_max_compress_level (bool) – Iff true, client accepts “maximum compression level” parameter.

  • request_max_compress_level (int) – Iff non-zero, client requests given “maximum compression level” - must be 1-9.

get_extension_string()[source]

Returns the WebSocket extension configuration string as sent to the server.

Returns

PMCE configuration string.

Return type

str

classmethod parse(params)[source]

Parses a WebSocket extension offer for permessage-bzip2 provided by a client to a server.

Parameters

params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns

object – A new instance of autobahn.compress.PerMessageBzip2Offer.

class autobahn.websocket.compress.PerMessageBzip2OfferAccept(offer, request_max_compress_level=0, compress_level=None)[source]

Set of parameters with which to accept an permessage-bzip2 offer from a client by a server.

Constructor.

Parameters
  • offer (Instance of autobahn.compress.PerMessageBzip2Offer.) – The offer being accepted.

  • request_max_compress_level (int) – Iff non-zero, server requests given “maximum compression level” - must be 1-9.

  • compress_level (int) – Override server (“server-to-client direction”) compress level (this must be compatible with offer).

get_extension_string()[source]

Returns the WebSocket extension configuration string as sent to the server.

Returns

PMCE configuration string.

Return type

str

class autobahn.websocket.compress.PerMessageBzip2Response(client_max_compress_level, server_max_compress_level)[source]

Set of parameters for permessage-bzip2 responded by server.

classmethod parse(params)[source]

Parses a WebSocket extension response for permessage-bzip2 provided by a server to a client.

Parameters

params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns

A new instance of autobahn.compress.PerMessageBzip2Response.

Return type

obj

class autobahn.websocket.compress.PerMessageBzip2ResponseAccept(response, compress_level=None)[source]

Set of parameters with which to accept an permessage-bzip2 response from a server by a client.

Parameters
  • response (Instance of autobahn.compress.PerMessageBzip2Response.) – The response being accepted.

  • compress_level (int) – Override client (“client-to-server direction”) compress level (this must be compatible with response).

class autobahn.websocket.compress.PerMessageCompress[source]

Base class for WebSocket compression negotiated parameters.

class autobahn.websocket.compress.PerMessageCompressOffer[source]

Base class for WebSocket compression parameter client offers.

class autobahn.websocket.compress.PerMessageCompressOfferAccept[source]

Base class for WebSocket compression parameter client offer accepts by the server.

class autobahn.websocket.compress.PerMessageCompressResponse[source]

Base class for WebSocket compression parameter server responses.

class autobahn.websocket.compress.PerMessageCompressResponseAccept[source]

Base class for WebSocket compression parameter server response accepts by client.

class autobahn.websocket.compress.PerMessageDeflate(is_server, server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, mem_level, max_message_size=None)[source]

permessage-deflate WebSocket extension processor.

class autobahn.websocket.compress.PerMessageDeflateOffer(accept_no_context_takeover=True, accept_max_window_bits=True, request_no_context_takeover=False, request_max_window_bits=0)[source]

Set of extension parameters for permessage-deflate WebSocket extension offered by a client to a server.

Parameters
  • accept_no_context_takeover (bool) – When True, the client accepts the “no context takeover” feature.

  • accept_max_window_bits (bool) – When True, the client accepts setting “max window size”.

  • request_no_context_takeover (bool) – When True, the client request the “no context takeover” feature.

  • request_max_window_bits (int) – When non-zero, the client requests the given “max window size” (must be and integer from the interval [9..15]).

get_extension_string()[source]

Returns the WebSocket extension configuration string as sent to the server.

Returns

PMCE configuration string.

Return type

str

classmethod parse(params)[source]

Parses a WebSocket extension offer for permessage-deflate provided by a client to a server.

Parameters

params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns

A new instance of autobahn.compress.PerMessageDeflateOffer.

Return type

obj

class autobahn.websocket.compress.PerMessageDeflateOfferAccept(offer, request_no_context_takeover=False, request_max_window_bits=0, no_context_takeover=None, window_bits=None, mem_level=None, max_message_size=None)[source]

Set of parameters with which to accept an permessage-deflate offer from a client by a server.

Parameters
  • offer (Instance of autobahn.compress.PerMessageDeflateOffer.) – The offer being accepted.

  • request_no_context_takeover (bool) – When True, the server requests the “no context takeover” feature.

  • request_max_window_bits – When non-zero, the server requests the given “max window size” (must be and integer from the interval [9..15]).

  • request_max_window_bits – int

  • no_context_takeover (bool) – Override server (“server-to-client direction”) context takeover (this must be compatible with the offer).

  • window_bits (int) – Override server (“server-to-client direction”) window size (this must be compatible with the offer).

  • mem_level (int) – Set server (“server-to-client direction”) memory level.

get_extension_string()[source]

Returns the WebSocket extension configuration string as sent to the server.

Returns

PMCE configuration string.

Return type

str

class autobahn.websocket.compress.PerMessageDeflateResponse(client_max_window_bits, client_no_context_takeover, server_max_window_bits, server_no_context_takeover)[source]

Set of parameters for permessage-deflate responded by server.

Parameters
  • client_max_window_bits (int) – FIXME

  • client_no_context_takeover (bool) – FIXME

  • server_max_window_bits (int) – FIXME

  • server_no_context_takeover (bool) – FIXME

classmethod parse(params)[source]

Parses a WebSocket extension response for permessage-deflate provided by a server to a client.

Parameters

params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns

A new instance of autobahn.compress.PerMessageDeflateResponse.

Return type

obj

class autobahn.websocket.compress.PerMessageDeflateResponseAccept(response, no_context_takeover=None, window_bits=None, mem_level=None, max_message_size=None)[source]

Set of parameters with which to accept an permessage-deflate response from a server by a client.

Parameters
  • response (Instance of autobahn.compress.PerMessageDeflateResponse.) – The response being accepted.

  • no_context_takeover (bool) – Override client (“client-to-server direction”) context takeover (this must be compatible with response).

  • window_bits (int) – Override client (“client-to-server direction”) window size (this must be compatible with response).

  • mem_level (int) – Set client (“client-to-server direction”) memory level.

class autobahn.websocket.compress.PerMessageSnappy(is_server, server_no_context_takeover, client_no_context_takeover)[source]

permessage-snappy WebSocket extension processor.

class autobahn.websocket.compress.PerMessageSnappyOffer(accept_no_context_takeover=True, request_no_context_takeover=False)[source]

Set of extension parameters for permessage-snappy WebSocket extension offered by a client to a server.

Parameters
  • accept_no_context_takeover (bool) – Iff true, client accepts “no context takeover” feature.

  • request_no_context_takeover (bool) – Iff true, client request “no context takeover” feature.

get_extension_string()[source]

Returns the WebSocket extension configuration string as sent to the server.

Returns

PMCE configuration string.

Return type

str

classmethod parse(params)[source]

Parses a WebSocket extension offer for permessage-snappy provided by a client to a server.

Parameters

params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns

A new instance of autobahn.compress.PerMessageSnappyOffer.

Return type

obj

class autobahn.websocket.compress.PerMessageSnappyOfferAccept(offer, request_no_context_takeover=False, no_context_takeover=None)[source]

Set of parameters with which to accept an permessage-snappy offer from a client by a server.

Parameters
  • offer (Instance of autobahn.compress.PerMessageSnappyOffer.) – The offer being accepted.

  • request_no_context_takeover (bool) – Iff true, server request “no context takeover” feature.

  • no_context_takeover (bool) – Override server (“server-to-client direction”) context takeover (this must be compatible with offer).

get_extension_string()[source]

Returns the WebSocket extension configuration string as sent to the server.

Returns

PMCE configuration string.

Return type

str

class autobahn.websocket.compress.PerMessageSnappyResponse(client_no_context_takeover, server_no_context_takeover)[source]

Set of parameters for permessage-snappy responded by server.

classmethod parse(params)[source]

Parses a WebSocket extension response for permessage-snappy provided by a server to a client.

Parameters

params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns

A new instance of autobahn.compress.PerMessageSnappyResponse.

Return type

obj

class autobahn.websocket.compress.PerMessageSnappyResponseAccept(response, no_context_takeover=None)[source]

Set of parameters with which to accept an permessage-snappy response from a server by a client.

Parameters
  • response (Instance of autobahn.compress.PerMessageSnappyResponse.) – The response being accepted.

  • no_context_takeover (bool) – Override client (“client-to-server direction”) context takeover (this must be compatible with response).

WebSocket Utilities

WebSocket utilities that do not depend on the specific networking framework being used (Twisted or asyncio).

autobahn.websocket.util.create_url(hostname, port=None, isSecure=False, path=None, params=None)[source]

Create a WebSocket URL from components.

Parameters
  • hostname (str) – WebSocket server hostname (for TCP/IP sockets) or filesystem path (for Unix domain sockets).

  • port (int or str) – For TCP/IP sockets, WebSocket service port or None (to select default ports 80 or 443 depending on isSecure. When hostname=="unix", this defines the path to the Unix domain socket instead of a TCP/IP network socket.

  • isSecure (bool) – Set True for secure WebSocket (wss scheme).

  • path (str) – WebSocket URL path of addressed resource (will be properly URL escaped). Ignored for RawSocket.

  • params (dict) – A dictionary of key-values to construct the query component of the addressed WebSocket resource (will be properly URL escaped). Ignored for RawSocket.

Returns

Constructed WebSocket URL.

Return type

str

autobahn.websocket.util.parse_url(url)[source]

Parses as WebSocket URL into it’s components and returns a tuple:

  • isSecure is a flag which is True for wss URLs.

  • host is the hostname or IP from the URL.

and for TCP/IP sockets:

  • tcp_port is the port from the URL or standard port derived from scheme (rs => 80, rss => 443).

or for Unix domain sockets:

  • uds_path is the path on the local host filesystem.

Parameters

url (str) – A valid WebSocket URL, i.e. ws://localhost:9000 for TCP/IP sockets or ws://unix:/tmp/file.sock for Unix domain sockets (UDS).

Returns

A 6-tuple (isSecure, host, tcp_port, resource, path, params) (TCP/IP) or (isSecure, host, uds_path, resource, path, params) (UDS).

Return type

tuple