XML Stream

1.6 Documentation

«  Stanza Matchers   ::   Contents   ::   XML Serialization  »

XML Stream

class slixmpp.xmlstream.xmlstream.XMLStream(host='', port=0)[source]

An XML stream connection manager and event dispatcher.

The XMLStream class abstracts away the issues of establishing a connection with a server and sending and receiving XML “stanzas”. A stanza is a complete XML element that is a direct child of a root document element. Two streams are used, one for each communication direction, over the same socket. Once the connection is closed, both streams should be complete and valid XML documents.

Three types of events are provided to manage the stream:

Triggered based on received stanzas, similar in concept to events in a SAX XML parser.


Triggered manually.


Triggered based on time delays.

Typically, stanzas are first processed by a stream event handler which will then trigger custom events to continue further processing, especially since custom event handlers may run in individual threads.

  • socket – Use an existing socket for the stream. Defaults to None to generate a new socket.

  • host (string) – The name of the target server.

  • port (int) – The port to use for the connection. Defaults to 0.


Forcibly close the connection

add_event_handler(name, pointer, disposable=False)[source]

Add a custom event handler that will be executed whenever its event is manually triggered.

  • name – The name of the event that will trigger this handler.

  • pointer – The function to execute.

  • disposable – If set to True, the handler will be discarded after one use. Defaults to False.

add_filter(mode, handler, order=None)[source]

Add a filter for incoming or outgoing stanzas.

These filters are applied before incoming stanzas are passed to any handlers, and before outgoing stanzas are put in the send queue.

Each filter must accept a single stanza, and return either a stanza or None. If the filter returns None, then the stanza will be dropped from being processed for events or from being sent.

  • mode – One of 'in' or 'out'.

  • handler – The filter function.

  • order (int) – The position to insert the filter in the list of active filters.


The desired, or actual, address of the connected server.


Path to a file containing certificates for verifying the server SSL certificate. A non-None value will trigger certificate checking.


On Mac OS X, certificates in the system keyring will be consulted, even if they are not in the provided file.


Immediately cancel the current create_connection() Future. This is useful when a client using slixmpp tries to connect on flaky networks, where sometimes a connection just gets lost and it needs to reconnect while the attempt is still ongoing.


Path to a file containing a client certificate to use for authenticating via SASL EXTERNAL. If set, there must also be a corresponding :attr:keyfile value.


The list of accepted ciphers, in OpenSSL Format. It might be useful to override it for improved security over the python defaults.

configure_dns(resolver, domain=None, port=None)[source]

Configure and set options for a Resolver instance, and other DNS related tasks. For example, you can also check getaddrinfo() to see if you need to call out to libresolv.so.2 to run res_init().

Meant to be overridden.

  • resolver – A Resolver instance or None if dnspython is not installed.

  • domain – The initial domain under consideration.

  • port – The initial port under consideration.


Set timeout and other options for self.socket.

Meant to be overridden.

connect(host='', port=0, use_ssl=False, force_starttls=True, disable_starttls=False)[source]

Create a new socket and connect to the server.

  • host – The name of the desired server for the connection.

  • port – Port to connect to on the server.

  • use_ssl – Flag indicating if SSL should be used by connecting directly to a port using SSL. If it is False, the connection will be upgraded to SSL/TLS later, using STARTTLS. Only use this value for old servers that have specific port for SSL/TLS

  • force_starttls – If True, the connection will be aborted if the server does not initiate a STARTTLS negotiation. If None, the connection will be upgraded to TLS only if the server initiate the STARTTLS negotiation, otherwise it will connect in clear. If False it will never upgrade to TLS, even if the server provides it. Use this for example if you’re on localhost


On any kind of disconnection, initiated by us or not. This signals the closure of the TCP connection


Called when the TCP connection has been established with the server


Called when incoming data is received on the socket.

We feed that data to the parser and the see if this produced any XML event. This could trigger one or more event (a stanza is received, the stream is opened, etc).


The domain to try when querying DNS records.


The default namespace of the stream content, not of the stream wrapper itself.


The default port to return when querying DNS records.

del_event_handler(name, pointer)[source]

Remove a function as a handler for an event.

  • name – The name of the event.

  • pointer – The function to remove as a handler.

del_filter(mode, handler)[source]

Remove an incoming or outgoing filter.

disconnect(wait=2.0, reason=None, ignore_send_queue=False)[source]

Close the XML stream and wait for an acknowldgement from the server for at most wait seconds. After the given number of seconds has passed without a response from the server, or when the server successfully responds with a closure of its own stream, abort() is called. If wait is 0.0, this will call abort() directly without closing the stream.

Does nothing if we are not connected.


wait (float) – Time to wait for a response from the server.

Return type



The reason why we are disconnecting from the server


An asyncio Future being done when the stream is disconnected.


A list of DNS results that have not yet been tried.


The service name to check with DNS SRV records. For example, setting this to 'xmpp-client' would query the _xmpp-client._tcp service.


Flag for controlling if the session can be considered ended if the connection is terminated.


When the TCP connection is properly closed by the remote end

event(name, data={})[source]

Manually trigger a custom event.

  • name – The name of the event to trigger.

  • data – Data that will be passed to each event handler. Defaults to an empty dictionary, but is usually a stanza object.


Returns the number of registered handlers for an event.


name – The name of the event to check.


Process an unknown exception.

Meant to be overridden.


exception – An unhandled exception object.

async get_dns_records(domain, port=None)[source]

Get the DNS records for a domain.

  • domain – The domain in question.

  • port – If the results don’t include a port, use this one.


Get SSL context.


Filter incoming XML objects before they are processed.

Possible uses include remapping namespaces, or correcting elements from sources with incorrect behavior.

Meant to be overridden.


init the XML parser. The parser must always be reset for each new connexion


Path to a file containing the private key for the selected client certificate to use for authenticating via SASL EXTERNAL.


A mapping of XML namespaces to well-known prefixes.


Generate and return a new stream ID in hexadecimal form.

Many stanzas, handlers, or matchers may require unique ID values. Using this method ensures that all new ID values are unique in this stream.

async pick_dns_answer(domain, port=None)[source]

Pick a server and port from DNS answers.

Gets DNS answers if none available. Removes used answer from available answers.

  • domain – The domain in question.

  • port – If the results don’t include a port, use this one.

process(*, forever=True, timeout=None)[source]

Process all the available XMPP events (receiving or sending data on the socket(s), calling various registered callbacks, calling expired timers, handling signal events, etc). If timeout is None, this function will run forever. If timeout is a number, this function will return after the given time in seconds.


An optional dictionary of proxy settings. It may provide: :host: The host offering proxy services. :port: The port for the proxy service. :username: Optional username for accessing the proxy. :password: Optional password for accessing the proxy.

reconnect(wait=2.0, reason='Reconnecting')[source]

Calls disconnect(), and once we are disconnected (after the timeout, or when the server acknowledgement is received), call connect()

register_handler(handler, before=None, after=None)[source]

Add a stream event handler that will be executed when a matching stanza is received.


handler – The BaseHandler derived object to execute.


Add a stanza object class as a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that appear as substanzas of a root stanza do not need to be registered here. That is done using register_stanza_plugin() from slixmpp.xmlstream.stanzabase.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.


stanza_class – The top-level stanza object’s class.


Remove any stream event handlers with the given name.


name – The name of the handler.


Remove a stanza from being a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

async run_filters()[source]

Background loop that processes stanzas to send.

schedule(name, seconds, callback, args=(), kwargs={}, repeat=False)[source]

Schedule a callback function to execute after a given delay.

  • name – A unique name for the scheduled callback.

  • seconds – The time in seconds to wait before executing.

  • callback – A pointer to the function to execute.

  • args – A tuple of arguments to pass to the function.

  • kwargs – A dictionary of keyword arguments to pass to the function.

  • repeat – Flag indicating if the scheduled event should be reset and repeat after executing.

send(data, use_filters=True)[source]

A wrapper for send_raw() for sending stanza objects.

  • data – The ElementBase stanza to send on the stream.

  • use_filters (bool) – Indicates if outgoing filters should be applied to the given stanza data. Disabling filters is useful when resending stanzas. Defaults to True.


Send raw data across the stream.


data (string) – Any bytes or utf-8 string value.


Send an XML object on the stream


data – The Element XML object to send on the stream.


Perform any initialization actions, such as handshakes, once the stream header has been sent.

Meant to be overridden.

async start_tls()[source]

Perform handshakes for TLS.

If the handshake is successful, the XML stream will need to be restarted.

The default closing tag for the stream element.


The default opening tag for the stream element.


The namespace of the enveloping stream element.


If set to True, allow using the dnspython DNS library if available. If set to False, the builtin DNS resolver will be used, even if dnspython is installed.


Use CDATA for escaping instead of XML entities. Defaults to False.


If set to True, attempt to use IPv6.


If set to True, attempt to connect through an HTTP proxy based on the settings in proxy_config.


Enable connecting to the server directly over SSL, in particular when the service provides two ports: one for non-SSL traffic and another for SSL traffic.

async wait_until(event, timeout=30)[source]

Utility method to wake on the next firing of an event. (Registers a disposable handler on it)

  • event (str) – Event to wait on.

  • timeout (int) – Timeout

Return type



If True, periodically send a whitespace character over the wire to keep the connection alive. Mainly useful for connections traversing NAT.


The default interval between keepalive signals when whitespace_keepalive is enabled.

«  Stanza Matchers   ::   Contents   ::   XML Serialization  »