本文整理汇总了Python中twisted.names.srvconnect.SRVConnector.connect方法的典型用法代码示例。如果您正苦于以下问题:Python SRVConnector.connect方法的具体用法?Python SRVConnector.connect怎么用?Python SRVConnector.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.names.srvconnect.SRVConnector
的用法示例。
在下文中一共展示了SRVConnector.connect方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def start(self):
myJid = jid.JID(self.username)
factory = client.XMPPClientFactory(myJid, self.password)
factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authd)
connector = SRVConnector(reactor, 'xmpp-client', self.jabberserver, factory)
reactor.callLater(5, self.stop)
connector.connect()
示例2: _getConnection
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def _getConnection(self):
if self.host:
return reactor.connectTCP(self.host, self.port, self.factory)
else:
c = SRVConnector(reactor, 'xmpp-client', self.domain, self.factory)
c.connect()
return c
示例3: __init__
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def __init__(self, client_jid, secret):
f = client.XMPPClientFactory(client_jid, secret)
f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.connected)
f.addBootstrap(xmlstream.STREAM_END_EVENT, self.disconnected)
f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
f.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.init_failed)
connector = SRVConnector(reactor, 'xmpp-client', client_jid.host, f,
defaultPort=5222)
connector.connect()
示例4: connect
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def connect(self):
if callable(self.override):
self.override(self.factory)
elif not self._isQueryNeeded():
self.factory.doStart()
self.factory.startedConnecting(self)
self._reallyConnect()
else:
SRVConnector.connect(self)
示例5: connectSRV
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def connectSRV(self, service, domain, *args, **kwargs):
SRVConnector = kwargs.pop('ConnectorClass', None)
if SRVConnector is None:
from twisted.names.srvconnect import SRVConnector
gtransport, factory = self._make_transport_and_factory()
c = SRVConnector(self.reactor, service, domain, factory, *args, **kwargs)
c.connect()
gtransport._init_transport()
return gtransport
示例6: __init__
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def __init__(self, reactor, jid, secret):
self.reactor = reactor
f = client.XMPPClientFactory(jid, secret)
f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.connected)
f.addBootstrap(xmlstream.STREAM_END_EVENT, self.disconnected)
f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
f.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.init_failed)
connector = SRVConnector(reactor, "xmpp-client", jid.host, f, defaultPort=5222)
connector.connect()
self.finished = Deferred()
示例7: __init__
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def __init__(self, service):
jid = JID('127.0.0.1')
f = client.XMPPClientFactory(jid, '')
f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.connected)
f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
connector = SRVConnector(
reactor, 'xmpp-client', jid.host, f, defaultPort=6523)
connector.connect()
self.finished = Deferred()
self.files = {}
self.service = service
示例8: connect
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def connect(self, protocolFactory):
def _canceller(deferred):
connector.stopConnecting()
deferred.errback(
error.ConnectingCancelledError(connector.getDestination()))
try:
wf = _WrappingFactory(protocolFactory, _canceller)
connector = SRVConnector(self._reactor, self._service,
self._domain, wf, protocol=self._protocol)
connector.connect()
return wf._onConnection
except:
return defer.fail()
示例9: connect
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def connect(self, server_address, service=None, protocol='tcp'):
"""
Connect to the given server_address.
Without the 'service' keyword, the server_address can be formatted
as HOST[:PORT] (if no port given, 8800 will be assumed).
If 'service' is used, it must be the name of a service to look up
using a DNS SRV record at the server_address (in this case, no port is
expected in the server_address). The 'protocol' is also sent used in
the DNS SRV lookup.
The 'protocol' keyword is ignored if 'service' is not used.
Examples:
c = Client()
# connect to example.com at port 8800
c.connect('example.com')
# connect to example.com at port 45
c.connect('example.com:45')
# look up the host and port using SRV, passing 'SIP' as the
## service name to the DNS SRV host at example.com
c.connect('example.com', service='SIP')
TODO: Twisted uses it's own lookup cache that appears to be
cleared when the process terminates. I am unsure whether that
cache respects SRV TTL; if not, long-living reconnecting
clients *might* not get a new lookup. Further testing is needed
to determine this.
"""
self.ip = server_address
if service:
connector = SRVConnector(reactor, service, server_address,
self.factory, protocol=protocol)
connector.connect()
else:
self.host, self.port = utils.parse_host_port(server_address, 8800)
try:
reactor.connectTCP(self.host, self.port, self.factory)
except error.ConnectionRefusedError, e:
logger.error(e)
# wraps the error in a slightly more generic ClientError
## and reraises
raise ClientError(str(e))
示例10: connectSSL
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def connectSSL(self, server_address, cert_path, cert_chain_path=None,
service=None, protocol='ssl'):
"""
Connect to the given server_address.
See the docstring for Client.connect() for more information.
"""
self.ip = server_address
# verify that the given key/cert files actually exist
if not os.path.exists(cert_path):
raise ClientError('Cert file %r does not exist!' % cert_path)
if cert_chain_path and not os.path.exists(cert_chain_path):
raise ClientError('Cert chain file %r does not exist!' % \
cert_chain_path)
class CtxFactory(ssl.ClientContextFactory):
def getContext(self):
self.method = SSL.SSLv23_METHOD
ctx = ssl.ClientContextFactory.getContext(self)
if cert_chain_path:
ctx.use_certificate_chain_file(cert_chain_path)
ctx.use_certificate_file(cert_path)
return ctx
if service:
connector = SRVConnector(reactor, service, server_address,
self.factory, protocol=protocol, connectFuncName='connectSSL',
connectFuncArgs=(CtxFactory(),))
connector.connect()
else:
self.host, self.port = utils.parse_host_port(server_address, 2220)
try:
reactor.connectSSL(self.host, self.port, self.factory,
CtxFactory())
except error.ConnectionRefusedError, e:
logger.error(e)
# wraps the error in a slightly more generic ClientError
## and reraises
raise ClientError(str(e))
示例11: clientConnectionLost
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def clientConnectionLost(self, connector, err):
print "Connection lost"
print err.value
reactor.callLater(0, reactor.stop)
if __name__ == "__main__":
if len(sys.argv) < 2 or len(sys.argv) > 4:
print "Usage: %s [email protected] [relay-hostname [relay-port]]" % sys.argv[0]
print "If the hostname and port are not specified, the MSRP relay will be discovered"
print "through the the _msrps._tcp.domain SRV record. If a hostname is specified but"
print "no port, the default port of 2855 will be used."
else:
username, domain = sys.argv[1].split("@", 1)
cred = X509Credentials(None, None)
cred.verify_peer = False
ctx = TLSContext(cred)
password = getpass()
if len(sys.argv) == 2:
factory = MSRPFileReceiverFactory(username, password, URI(domain, use_tls=True))
connector = SRVConnector(reactor, "msrps", domain, factory, connectFuncName="connectTLS", connectFuncArgs=[ctx])
connector.connect()
else:
relay_host = sys.argv[2]
if len(sys.argv) == 4:
relay_port = int(sys.argv[3])
else:
relay_port = 2855
factory = MSRPFileReceiverFactory(username, password, URI(relay_host, port=relay_port, use_tls=True))
reactor.connectTLS(relay_host, relay_port, factory, ctx)
reactor.run()
示例12: XMPP
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
class XMPP(Listener):
def init(self):
self.username, self.server = self.mirror('username').split('@')
self.password = self.mirror('password')
listener = self.parent().get_listener(self._id)
self.resource = listener['resource']
self.nickname = listener['nickname']
jid = "%[email protected]%s/%s" % (self.username, self.server, self.resource)
self.jid = JID(jid)
self.f = client.XMPPClientFactory(self.jid, self.password)
self.con = SRVConnector(
reactor, 'xmpp-client', self.jid.host, self.f, defaultPort=5222)
#self.con.connect()
def is_twisted(self):
return True
def handlers(self):
# Register event handlers.
self.f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.on_connected)
self.f.addBootstrap(xmlstream.STREAM_END_EVENT, self.on_disconnected)
self.f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.on_authenticated)
self.f.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.on_init_failed)
pass
def signon(self):
# Log in.
self.con.connect()
self.online(True)
def loop(self):
pass
def rawDataIn(self, buf):
#print "RECV: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')
pass
def rawDataOut(self, buf):
#print "SEND: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')
pass
def send_message(self, to, content):
message = domish.Element(('jabber:client', 'message'))
message['to'] = JID(to).full()
message['type'] = 'chat'
message.addElement('body', 'jabber:client', content)
self.xmlstream.send(message)
def allow_subscribe(self, to):
"""Respond to an add (subscribe) request by allowing it."""
message = domish.Element({'jabber:client', 'presence'})
message['to'] = JID(to).full()
message['type'] = 'subscribed'
self.xmlstream.send(message)
def deny_subscribe(self, to):
"""Respond to somebody removing us from their contact list."""
message = domish.Element({'jabber:client', 'presence'})
message['to'] = JID(to).full()
message['type'] = 'unsubscribed'
self.xmlstream.send(message)
def on_connected(self, xs):
#print 'Connected.'
self.xmlstream = xs
# Log all traffic.
xs.rawDataInFn = self.rawDataIn
xs.rawDataOutFn = self.rawDataOut
def on_disconnected(self, xs):
#print 'Disconnected.'
pass
def on_authenticated(self, xs):
#print 'Authenticated.'
presence = domish.Element(('jabber:client', 'presence'))
xs.send(presence)
# Register event handlers.
xs.addObserver('/message', self.on_message)
xs.addObserver('/presence', self.on_presence)
xs.addObserver('/*', self.debug)
# xs.sendFooter()
# reactor.callLater(5, xs.sendFooter)
def on_init_failed(self, failure):
print 'Initialization failure.'
print failure
def on_message(self, el):
#print "Received message!"
# The sender.
source = str(el['from'])
username = singleton.format_name('XMPP', source.split("/")[0])
# Get the chat body.
#.........这里部分代码省略.........
示例13: clientCreator
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
def clientCreator(factory):
domain = factory.authenticator.jid.host
c = SRVConnector(reactor, 'xmpp-client', domain, factory)
c.connect()
return factory.deferred
示例14: __init__
# 需要导入模块: from twisted.names.srvconnect import SRVConnector [as 别名]
# 或者: from twisted.names.srvconnect.SRVConnector import connect [as 别名]
class XMPPClient:
'''
The XMPPClients uses the username, server and password to connect to the xmpp server.
A message can be send using the sendMessage function, received presences and messages
can be processed by a callback function.
If the connection fails or is lost, the client will try to reconnect automatically.
The disconnectedCallback can be used to catch the connection failed or connection lost event.
At startup, a watchdog is started: if the server can't authenticate the user within the
timeOut, the connection will be closed and the disconnectedCallback will be called.
'''
def __init__(self, username, server, password, hostname, timeOut=5):
self.username = username
self.server = server
self.password = password
self.timeOut = timeOut
self.hostname = hostname
self.xmpp_user = None
self.status = 'NOT_CONNECTED'
self.messageReceivedCallback = None
self.presenceReceivedCallback = None
self.connectedCallback = None
self.disconnectedCallback = None
self.connector = None
self.xmlstream = None
def start(self):
''' Start the xmpp client, opens the connection to the server '''
if self.status <> 'NOT_CONNECTED':
raise RuntimeError('The XmppClient has already been started.')
q.logger.log("[XMPPCLIENT] Starting the xmpp client to " + self.username + "@" + self.server, 5)
self.startup_watchdog = reactor.callLater(self.timeOut, self._watchdog_timeout)
self._connect()
def stop(self):
''' Stop the xmpp client '''
if self.status == 'NOT_CONNECTED':
raise RuntimeError('The XmppClient has not yet been started.')
q.logger.log("[XMPPCLIENT] Stopping the xmpp client to " + self.username + "@" + self.server, 5)
self.connector.disconnect()
def sendMessage(self, to, type, id, message=' '):
''' Send a message
@param to: The username of the client to send the message to
@type to: string
@param type: The type of the message
@type type: string
@param id: The id of the message
@type id: string
@param message: The message to send
@type message: string
'''
if self.status <> 'RUNNING':
raise NotConnectedException()
q.logger.log("[XMPPCLIENT] Sending message '" + str(id) + "' of type '" + str(type) +"' to " + str(to) + " for " + self.username + "@" + self.server, 5)
elemToSend = domish.Element(('jabber:client','message'), attribs={'to':to+"@"+self.server, 'type':type, 'id':id})
body = domish.Element((None, 'body'))
body.addContent(message)
elemToSend.addContent(body)
self.xmlstream.send(elemToSend)
def sendPresence(self, to=None, type=None):
''' Send a presence
@param to: The username of the client to send the presence to. None=send to all your friends
@type to: string
@param type: The type of the presence. Possible values: None=available, unavailable, subscribe, subscribed
@type type: string
'''
if self.status <> 'RUNNING':
raise NotConnectedException()
q.logger.log("[XMPPCLIENT] Sending presence of type '" + str(type) +"' to " + str(to) + "'", 5)
attribs={}
if to <> None: attribs['to'] = to+"@"+self.server
if type <> None: attribs['type'] = type
presence = domish.Element(('jabber:client','presence'), attribs=attribs)
self.xmlstream.send(presence)
def _presence_received(self, elem):
fromm = elem.getAttribute('from').split("@")[0]
if not elem.hasAttribute('type'):
type = 'available'
else:
type = elem.getAttribute('type')
q.logger.log("[XMPPCLIENT] Presence received from '" + fromm + "' of type '" + type +"'", 5)
if self.presenceReceivedCallback:
#.........这里部分代码省略.........