'Perform binding. Use provided resource name or random (if not provided).'

def Bind(self, resource=None):

    while ((self.bound is None) and self._owner.Process(1)):
        pass
    if resource:
        resource = [Node('resource', payload=[resource])]
    else:
        resource = []
    resp = self._owner.SendAndWaitForResponse(Protocol('iq', typ='set', payload=[Node('bind', attrs={'xmlns': NS_BIND}, payload=resource)]))
    if isResultNode(resp):
        self.bound.append(resp.getTag('bind').getTagData('jid'))
        self.DEBUG(('Successfully    bound    %s.' % self.bound[(-1)]), 'ok')
        jid = JID(resp.getTag('bind').getTagData('jid'))
        self._owner.User = jid.getNode()
        self._owner.Resource = jid.getResource()
        resp = self._owner.SendAndWaitForResponse(Protocol('iq', typ='set', payload=[Node('session', attrs={'xmlns': NS_SESSION})]))
        if isResultNode(resp):
            self.DEBUG('Successfully    opened    session.', 'ok')
            self.session = 1
            return 'ok'
        else:
            self.DEBUG('Session    open    failed.', 'error')
            self.session = 0
    elif resp:
        self.DEBUG(('Binding    failed:    %s.' % resp.getTag('error')), 'error')
    else:
        self.DEBUG('Binding    failed:    timeout    expired.', 'error')
        return ''
