autobahn.websocket.interfaces


Module Contents

Classes

IWebSocketServerChannelFactory

WebSocket server protocol factories implement this interface, and create

IWebSocketClientChannelFactory

WebSocket client protocol factories implement this interface, and create

IWebSocketChannel

A WebSocket channel is a bidirectional, full-duplex, ordered, reliable message channel

IWebSocketChannelFrameApi

Frame-based API to a WebSocket channel.

IWebSocketChannelStreamingApi

Streaming API to a WebSocket channel.

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

Bases: abc.ABC

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

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).

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 resetProtocolOptions()[source]

Reset all WebSocket protocol options to defaults.

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

Bases: abc.ABC

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

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

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 resetProtocolOptions()[source]

Reset all WebSocket protocol options to defaults.

class autobahn.websocket.interfaces.IWebSocketChannel[source]

Bases: abc.ABC

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 onConnecting(transport_details: autobahn.wamp.types.TransportDetails) Optional[autobahn.websocket.types.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 onConnect(request_or_response: Union[autobahn.websocket.types.ConnectionRequest, autobahn.websocket.types.ConnectionResponse]) Union[Optional[str], 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 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 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 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 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 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 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 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 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.

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.

class autobahn.websocket.interfaces.IWebSocketChannelFrameApi[source]

Bases: IWebSocketChannel

Frame-based API to a WebSocket channel.

abstract onMessageBegin(isBinary: bool)[source]

Callback fired when receiving of a new WebSocket message has begun.

Parameters

isBinary (bool) – True if payload is binary, else the payload is UTF-8 encoded text.

abstract onMessageFrame(payload: bytes)[source]

Callback fired when a complete WebSocket message frame for a previously begun WebSocket message has been received.

Parameters

payload (list of bytes) – Message frame payload (a list of chunks received).

abstract onMessageEnd()[source]

Callback fired when a WebSocket message has been completely received (the last WebSocket frame for that message has been received).

abstract beginMessage(isBinary: bool = False, doNotCompress: bool = False)[source]

Begin sending a new WebSocket message.

Parameters
  • isBinary (bool) – True if payload is binary, else the payload must be UTF-8 encoded text.

  • doNotCompress (bool) – If True, never compress this message. This only applies to Hybi-Mode and only when WebSocket compression has been negotiated on the WebSocket connection. Use when you know the payload incompressible (e.g. encrypted or already compressed).

abstract sendMessageFrame(payload: bytes, sync: bool = False)[source]

When a message has been previously begun, send a complete message frame in one go.

Parameters
  • payload (bytes) – The message frame payload. When sending a text message, the payload must be UTF-8 encoded already.

  • sync (bool) –

    If True, try to force data onto the wire immediately.

    Warning

    Do NOT use this feature for normal applications. Performance likely will suffer significantly. This feature is mainly here for use by Autobahn|Testsuite.

abstract endMessage()[source]

End a message previously begun message. No more frames may be sent (for that message). You have to begin a new message before sending again.

class autobahn.websocket.interfaces.IWebSocketChannelStreamingApi[source]

Bases: IWebSocketChannelFrameApi

Streaming API to a WebSocket channel.

abstract onMessageFrameBegin(length: int)[source]

Callback fired when receiving a new message frame has begun. A default implementation will prepare to buffer message frame data.

Parameters

length (int) – Payload length of message frame which is subsequently received.

abstract onMessageFrameData(payload: bytes)[source]

Callback fired when receiving data within a previously begun message frame. A default implementation will buffer data for frame.

Parameters

payload (bytes) – Partial payload for message frame.

abstract onMessageFrameEnd()[source]

Callback fired when a previously begun message frame has been completely received. A default implementation will flatten the buffered frame data and fire onMessageFrame.

abstract beginMessageFrame(length: int)[source]

Begin sending a new message frame.

Parameters

length (int) – Length of the frame which is to be started. Must be less or equal 2^63.

abstract sendMessageFrameData(payload: bytes, sync: bool = False)[source]

Send out data when within a message frame (message was begun, frame was begun). Note that the frame is automatically ended when enough data has been sent. In other words, there is no endMessageFrame, since you have begun the frame specifying the frame length, which implicitly defined the frame end. This is different from messages, which you begin and end explicitly , since a message can contain an unlimited number of frames.

Parameters
  • payload (bytes) – Frame payload to send.

  • sync (bool) –

    If True, try to force data onto the wire immediately.

    Warning

    Do NOT use this feature for normal applications. Performance likely will suffer significantly. This feature is mainly here for use by Autobahn|Testsuite.

Returns

When the currently sent message frame is still incomplete, returns octets remaining to be sent. When the frame is complete, returns 0. Otherwise the amount of unconsumed data in payload argument is returned.

Return type

int