autobahn.websocket.protocol¶
Classes¶
A protocol factory for WebSocket clients. |
|
Protocol base class for WebSocket clients. |
|
Mixin for |
|
Protocol base class for WebSocket. |
|
A protocol factory for WebSocket servers. |
|
Protocol base class for WebSocket servers. |
Module Contents¶
- class WebSocketClientFactory(url=None, origin=None, protocols=None, useragent='AutobahnPython/{}'.format(__version__), headers=None, proxy=None)[source]¶
Bases:
WebSocketFactoryA protocol factory for WebSocket clients.
Implements
autobahn.websocket.interfaces.IWebSocketClientChannelFactory()- protocol[source]¶
The protocol to be spoken. Must be derived from
autobahn.websocket.protocol.WebSocketClientProtocol.
- resetProtocolOptions()[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketClientChannelFactory.resetProtocolOptions()
- 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, autoPingRestartOnAnyTraffic=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketClientChannelFactory.setProtocolOptions()
- setSessionParameters(url=None, origin=None, protocols=None, useragent=None, headers=None, proxy=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketClientChannelFactory.setSessionParameters()
- class WebSocketClientProtocol[source]¶
Bases:
WebSocketProtocolProtocol base class for WebSocket clients.
- CONFIG_ATTRS = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask',...[source]¶
- _actuallyStartHandshake(request_options)[source]¶
Internal helper.
Actually send the WebSocket opening handshake after receiving valid request options.
- _connectionLost(reason)[source]¶
Called by network framework when established transport connection to server was lost. Default implementation will tear down all state properly. When overriding in derived class, make sure to call this base class implementation _after_ your code.
- _connectionMade()[source]¶
Called by network framework when new transport connection to server was established. Default implementation will start the initial WebSocket opening handshake (or proxy connect). When overriding in derived class, make sure to call this base class implementation _before_ your code.
- failHandshake(reason)[source]¶
During opening handshake the server response is invalid and we drop the connection.
- failProxyConnect(reason)[source]¶
During initial explicit proxy connect, the server response indicates some failure and we drop the connection.
- onConnect(response: autobahn.websocket.types.ConnectionResponse) NoneType[source]¶
Callback fired directly after WebSocket opening handshake when new WebSocket connection was established from the client to a server.
- Parameters:
response – WebSocket connection response information sent by server.
- onConnecting(transport_details: autobahn.wamp.types.TransportDetails) autobahn.websocket.types.ConnectingRequest | None[source]¶
Callback fired after the connection is established, but before the handshake has started. This may return a
autobahn.websocket.types.ConnectingRequestinstance (or a future which resolves to one) to control aspects of the handshake (or None for defaults)- Parameters:
transport_details – Details of the transport underlying the WebSocket connection being established.
- Returns:
A
autobahn.websocket.types.ConnectingRequestinstance is returned to indicate which options should be used for this connection. If you wish to use the default behavior,Nonemay be returned (this is the default).
- class WebSocketFactory[source]¶
Bases:
objectMixin for
autobahn.websocket.protocol.WebSocketClientFactoryandautobahn.websocket.protocol.WebSocketServerFactory.- prepareMessage(payload, isBinary=False, doNotCompress=False)[source]¶
Prepare a WebSocket message. This can be later sent on multiple instances of
autobahn.websocket.WebSocketProtocolusingautobahn.websocket.WebSocketProtocol.sendPreparedMessage().By doing so, you can avoid the (small) overhead of framing the same payload into WebSocket messages multiple times when that same payload is to be sent out on multiple connections.
- Parameters:
payload (bytes) – The message payload.
isBinary (bool) – True iff payload is binary, else the payload must be UTF-8 encoded text.
doNotCompress (bool) – Iff True, never compress this message. This only applies when WebSocket compression has been negotiated on the WebSocket connection. Use when you know the payload incompressible (e.g. encrypted or already compressed).
- Returns:
An instance of
autobahn.websocket.protocol.PreparedMessage.
- class WebSocketProtocol[source]¶
Bases:
autobahn.util.ObservableMixinProtocol base class for WebSocket.
This class implements:
- CLOSE_STATUS_CODE_ABNORMAL_CLOSE = 1006[source]¶
Abnormal close of connection. (MUST NOT be used as status code when sending a close).
- CLOSE_STATUS_CODE_INTERNAL_ERROR = 1011[source]¶
The peer encountered an unexpected condition or internal error.
- CLOSE_STATUS_CODE_NULL = 1005[source]¶
No status received. (MUST NOT be used as status code when sending a close).
- CLOSE_STATUS_CODE_TLS_HANDSHAKE_FAILED = 1015[source]¶
TLS handshake failed, i.e. server certificate could not be verified. (MUST NOT be used as status code when sending a close).
- CONFIG_ATTRS_CLIENT = ['version', 'acceptMaskedServerFrames', 'maskClientFrames', 'serverConnectionDropTimeout',...[source]¶
Configuration attributes specific to clients.
- CONFIG_ATTRS_COMMON = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask',...[source]¶
Configuration attributes common to servers and clients.
- CONFIG_ATTRS_SERVER = ['versions', 'webStatus', 'requireMaskedClientFrames', 'maskServerFrames',...[source]¶
Configuration attributes specific to servers.
- DEFAULT_SPEC_VERSION = 18[source]¶
final RFC6455.
- Type:
Default WebSocket protocol spec version this implementation speaks
- PROTOCOL_TO_SPEC_VERSION[source]¶
Mapping from protocol version to the latest protocol spec (draft) version using that protocol version.
- SUPPORTED_PROTOCOL_VERSIONS = [8, 13][source]¶
WebSocket protocol versions supported by this implementation.
- SUPPORTED_SPEC_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18][source]¶
WebSocket protocol spec (draft) versions supported by this implementation. Use of version 18 indicates RFC6455. Use of versions < 18 indicate actual draft spec versions (Hybi-Drafts).
- _QUEUED_WRITE_DELAY = 1e-05[source]¶
For synched/chopped writes, this is the reactor reentry delay in seconds.
- _WS_MAGIC = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'[source]¶
Protocol defined magic used during WebSocket handshake (used in Hybi-drafts and final RFC6455.
- _cancelAutoPingTimeoutCall()[source]¶
When data is received from client, use it in leu of timely PONG response - cancel pending timeout call that will drop connection. See https://github.com/crossbario/autobahn-python/issues/1327
- _connectionLost(reason)[source]¶
This is called by network framework when a transport connection was lost.
- _connectionMade()[source]¶
This is called by network framework when a new TCP connection has been established and handed over to a Protocol instance (an instance of this class).
- _dataReceived(data)[source]¶
This is called by network framework upon receiving data on transport connection.
- _fail_connection(code=CLOSE_STATUS_CODE_GOING_AWAY, reason='going away')[source]¶
Fails the WebSocket connection.
- _invalid_payload(reason)[source]¶
Fired when invalid payload is encountered. Currently, this only happens for text message when payload is invalid UTF-8 or close frames with close reason that is invalid UTF-8.
- Parameters:
reason (str) – What was invalid for the payload (human readable).
- Returns:
True, when any further processing should be discontinued.
- _parseExtensionsHeader(header, removeQuotes=True)[source]¶
Parse the Sec-WebSocket-Extensions header.
- _protocol_violation(reason)[source]¶
Fired when a WebSocket protocol violation/error occurs.
- Parameters:
reason (str) – Protocol violation that was encountered (human readable).
- Returns:
True, when any further processing should be discontinued.
- _send()[source]¶
Send out stuff from send queue. For details how this works, see test/trickling in the repo.
- _transport_details: autobahn.wamp.types.TransportDetails | None[source]¶
- _trigger()[source]¶
Trigger sending stuff from send queue (which is only used for chopped/synched writes).
- beginMessage(isBinary=False, doNotCompress=False)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.beginMessage()
- beginMessageFrame(length)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.beginMessageFrame()
- logRxFrame(frameHeader, payload)[source]¶
Hook fired right after WebSocket frame has been received and decoded, but only when self.logFrames == True.
- logRxOctets(data)[source]¶
Hook fired right after raw octets have been received, but only when self.logOctets == True.
- logTxFrame(frameHeader, payload, repeatLength, chopsize, sync)[source]¶
Hook fired right after WebSocket frame has been encoded and sent, but only when self.logFrames == True.
- logTxOctets(data, sync)[source]¶
Hook fired right after raw octets have been sent, but only when self.logOctets == True.
- onAutoPingTimeout()[source]¶
When doing automatic ping/pongs to detect broken connection, the peer did not reply in time to our ping. We drop the connection.
- onAutoPong(ping_sent, ping_seq, pong_received, pong_rtt, payload)[source]¶
When doing automatic ping/pongs, this is called upon a successful pong.
- Parameters:
ping_sent – Posix time in ns when ping was sent.
ping_seq – Sequence number of ping that was sent.
pong_received – Posix time in ns when pong was received.
pong_rtt – Pong roundtrip-time in ms measured.
payload – The complete WebSocket ping/pong message payload (ping_sent 8 bytes big-endian | ping_seq 4 bytes big endian | max. 113 optional random bytes).
- onClose(wasClean, code, reason)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onClose()
- onCloseFrame(code, reasonRaw)[source]¶
Callback when a Close frame was received. The default implementation answers by sending a Close when no Close was sent before. Otherwise it drops the TCP connection either immediately (when we are a server) or after a timeout (when we are a client and expect the server to drop the TCP).
- Parameters:
code (int) – Close status code, if there was one (
WebSocketProtocol.CLOSE_STATUS_CODE_*).reasonRaw (bytes) – Close reason (when present, a status code MUST have been also be present).
- onCloseHandshakeTimeout()[source]¶
We expected the peer to respond to us initiating a close handshake. It didn’t respond (in time self.closeHandshakeTimeout) with a close response frame though. So we drop the connection, but set self.wasClean = False.
- onMessage(payload, isBinary)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onMessage()
- onMessageBegin(isBinary)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onMessageBegin()
- onMessageFrame(payload)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrame()
- onMessageFrameBegin(length)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameBegin()
- onMessageFrameData(payload)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameData()
- onMessageFrameEnd()[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameEnd()
- onOpen()[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onOpen()
- onOpenHandshakeTimeout()[source]¶
We expected the peer to complete the opening handshake with to us. It didn’t do so (in time self.openHandshakeTimeout). So we drop the connection, but set self.wasClean = False.
- onPing(payload)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onPing()
- onPong(payload)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.onPong()
- onServerConnectionDropTimeout()[source]¶
We (a client) expected the peer (a server) to drop the connection, but it didn’t (in time self.serverConnectionDropTimeout). So we drop the connection, but set self.wasClean = False.
- processData()[source]¶
After WebSocket handshake has been completed, this procedure will do all subsequent processing of incoming bytes.
- sendClose(code=None, reason=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendClose()
- sendCloseFrame(code=None, reasonUtf8=None, isReply=False)[source]¶
Send a close frame and update protocol state. Note, that this is an internal method which deliberately allows not send close frame with invalid payload.
- sendData(data, sync=False, chopsize=None)[source]¶
Wrapper for self.transport.write which allows to give a chopsize. When asked to chop up writing to TCP stream, we write only chopsize octets and then give up control to select() in underlying reactor so that bytes get onto wire immediately. Note that this is different from and unrelated to WebSocket data message fragmentation. Note that this is also different from the TcpNoDelay option which can be set on the socket.
- sendFrame(opcode, payload=b'', fin=True, rsv=0, mask=None, payload_len=None, chopsize=None, sync=False)[source]¶
Send out frame. Normally only used internally via sendMessage(), sendPing(), sendPong() and sendClose().
This method deliberately allows to send invalid frames (that is frames invalid per-se, or frames invalid because of protocol state). Other than in fuzzing servers, calling methods will ensure that no invalid frames are sent.
In addition, this method supports explicit specification of payload length. When payload_len is given, it will always write that many octets to the stream. It’ll wrap within payload, resending parts of that when more octets were requested The use case is again for fuzzing server which want to sent increasing amounts of payload data to peers without having to construct potentially large messages themselves.
- sendMessage(payload, isBinary=False, fragmentSize=None, sync=False, doNotCompress=False)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendMessage()
- sendMessageFrame(payload, sync=False)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendMessageFrame()
- sendMessageFrameData(payload, sync=False)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendMessageFrameData()
- sendPing(payload=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendPing()
- sendPong(payload=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendPong()
- sendPreparedMessage(preparedMsg)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketChannel.sendPreparedMessage()
- setTrackTimings(enable)[source]¶
Enable/disable tracking of detailed timings.
- Parameters:
enable (bool) – Turn time tracking on/off.
- property transport_details: autobahn.wamp.types.TransportDetails | None[source]¶
Implements
autobahn.wamp.interfaces.ITransport.transport_details.
- class WebSocketServerFactory(url=None, protocols=None, server='AutobahnPython/{}'.format(__version__), headers=None, externalPort=None)[source]¶
Bases:
WebSocketFactoryA protocol factory for WebSocket servers.
Implements
autobahn.websocket.interfaces.IWebSocketServerChannelFactory()- getConnectionCount()[source]¶
Get number of currently connected clients.
- Returns:
Number of currently connected clients.
- protocol[source]¶
The protocol to be spoken. Must be derived from
autobahn.websocket.protocol.WebSocketServerProtocol.
- resetProtocolOptions()[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketServerChannelFactory.resetProtocolOptions()
- 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, autoPingRestartOnAnyTraffic=None, serveFlashSocketPolicy=None, flashSocketPolicy=None, allowedOrigins=None, allowNullOrigin=False, maxConnections=None, trustXForwardedFor=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketServerChannelFactory.setProtocolOptions()
- setSessionParameters(url=None, protocols=None, server=None, headers=None, externalPort=None)[source]¶
Implements
autobahn.websocket.interfaces.IWebSocketServerChannelFactory.setSessionParameters()
- class WebSocketServerProtocol[source]¶
Bases:
WebSocketProtocolProtocol base class for WebSocket servers.
- CONFIG_ATTRS = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask',...[source]¶
- _connectionLost(reason)[source]¶
Called by network framework when established transport connection from client was lost. Default implementation will tear down all state properly. When overriding in derived class, make sure to call this base class implementation after your code.
- _connectionMade()[source]¶
Called by network framework when new transport connection from client was accepted. Default implementation will prepare for initial WebSocket opening handshake. When overriding in derived class, make sure to call this base class implementation before your code.
- failHandshake(reason, code=400, responseHeaders=None)[source]¶
During opening handshake the client request was invalid, we send a HTTP error response and then drop the connection.
- onConnect(request: autobahn.websocket.types.ConnectionRequest) str | None | Tuple[str | None, Dict[str, str]][source]¶
Callback fired during WebSocket opening handshake when new WebSocket client connection is about to be established.
When you want to accept the connection, return the accepted protocol from list of WebSocket (sub)protocols provided by client or None to speak no specific one or when the client protocol list was empty.
You may also return a pair of (protocol, headers) to send additional HTTP headers, with headers being a dictionary of key-values.
Throw
autobahn.websocket.types.ConnectionDenywhen you don’t want to accept the WebSocket connection request.- Parameters:
request – WebSocket connection request information.
- Returns:
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. You can also return a Deferred/Future that resolves/rejects to the above.