'Extract stanzas from the send queue and send them on the stream.'

def _send_thread(self):

    try:
        while (not self.stop.is_set()):
            while ((not self.stop.is_set()) and (not self.session_started_event.is_set())):
                self.session_started_event.wait(timeout=0.1)
            if (self.__failed_send_stanza is not None):
                data = self.__failed_send_stanza
                self.__failed_send_stanza = None
            else:
                data = self.send_queue.get()
                if (data is None):
                    continue
            log.debug(u'SEND:    %s', data)
            enc_data = data.encode(u'utf-8')
            total = len(enc_data)
            sent = 0
            count = 0
            tries = 0
            try:
                with self.send_lock:
                    while ((sent < total) and (not self.stop.is_set()) and self.session_started_event.is_set()):
                        try:
                            sent += self.socket.send(enc_data[sent:])
                            count += 1
                        except ssl.SSLError as serr:
                            if (tries >= self.ssl_retry_max):
                                log.debug(u'SSL    error:    max    retries    reached')
                                self.exception(serr)
                                log.warning(u'Failed    to    send    %s', data)
                                if (not self.stop.is_set()):
                                    self.disconnect(self.auto_reconnect, send_close=False)
                                log.warning(u'SSL    write    error:    retrying')
                            if (not self.stop.is_set()):
                                time.sleep(self.ssl_retry_delay)
                            tries += 1
                        except Socket.error as serr:
                            if (serr.errno != errno.EINTR):
                                raise
                if (count > 1):
                    log.debug(u'SENT:    %d    chunks', count)
                self.send_queue.task_done()
            except (Socket.error, ssl.SSLError) as serr:
                self.event(u'socket_error', serr, direct=True)
                log.warning(u'Failed    to    send    %s', data)
                if (not self.stop.is_set()):
                    self.__failed_send_stanza = data
                    self._end_thread(u'send')
                    self.disconnect(self.auto_reconnect, send_close=False)
                    return
    except Exception as ex:
        log.exception(u'Unexpected    error    in    send    thread:    %s', ex)
        self.exception(ex)
        if (not self.stop.is_set()):
            self._end_thread(u'send')
            self.disconnect(self.auto_reconnect)
            return
    self._end_thread(u'send')
