python类connectTCP()的实例源码

test_tcp.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def testWriter(self):
        f = protocol.Factory()
        f.protocol = WriterProtocol
        f.done = 0
        f.problem = 0
        wrappedF = WiredFactory(f)
        p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
        n = p.getHost().port
        self.ports.append(p)
        clientF = WriterClientFactory()
        wrappedClientF = WiredFactory(clientF)
        reactor.connectTCP("127.0.0.1", n, wrappedClientF)

        def check(ignored):
            self.failUnless(f.done, "writer didn't finish, it probably died")
            self.failUnless(f.problem == 0, "writer indicated an error")
            self.failUnless(clientF.done,
                            "client didn't see connection dropped")
            expected = "".join(["Hello Cleveland!\n",
                                "Goodbye", " cruel", " world", "\n"])
            self.failUnless(clientF.data == expected,
                            "client didn't receive all the data it expected")
        d = defer.gatherResults([wrappedF.onDisconnect,
                                 wrappedClientF.onDisconnect])
        return d.addCallback(check)
test_tcp.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _testBuildProtocol(self, portno):
        f = AServerFactory(self, IPv4Address('TCP', '127.0.0.1', portno))
        wrappedF = FireOnListenFactory(f)
        p = reactor.listenTCP(0, wrappedF)
        self.ports.append(p)

        def client(ignored):
            acf = AClientFactory(self, IPv4Address("TCP", "127.0.0.1",
                                                   p.getHost().port))
            wired = WiredFactory(acf)
            reactor.connectTCP("127.0.0.1", p.getHost().port, wired,
                               bindAddress=("127.0.0.1", portno))
            d = wired.onConnect
            def _onConnect(ignored):
                self.ports.append(acf.protocol.transport)
                self.assert_(hasattr(self, "ran"))
                return wired.onDisconnect
            def _onDisconnect(ignored):
                del self.ran
            d.addCallback(_onConnect)
            d.addCallback(_onDisconnect)
            return d

        return wrappedF.deferred.addCallback(client)
test_factories.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def testStopTrying(self):
        f = Factory()
        f.protocol = In
        f.connections = 0
        f.allMessages = []
        f.goal = 2
        f.d = defer.Deferred()

        c = ReconnectingClientFactory()
        c.initialDelay = c.delay = 0.2
        c.protocol = Out
        c.howManyTimes = 2

        port = self.port = reactor.listenTCP(0, f)
        PORT = port.getHost().port
        reactor.connectTCP('127.0.0.1', PORT, c)

        f.d.addCallback(self._testStopTrying_1, f, c)
        return f.d
ftp.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def ftp_PORT(self, address):
        addr = map(int, address.split(','))
        ip = '%d.%d.%d.%d' % tuple(addr[:4])
        port = addr[4] << 8 | addr[5]

        # if we have a DTP port set up, lose it.
        if self.dtpFactory is not None:
            self.cleanupDTP()

        self.dtpFactory = DTPFactory(pi=self, peerHost=self.transport.getPeer().host)
        self.dtpFactory.setTimeout(self.dtpTimeout)
        self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory)

        def connected(ignored):
            return ENTERING_PORT_MODE
        def connFailed(err):
            err.trap(PortConnectionError)
            return CANT_OPEN_DATA_CNX
        return self.dtpFactory.deferred.addCallbacks(connected, connFailed)
client.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def lookupZone(self, name, timeout = 10):
        """
        Perform an AXFR request. This is quite different from usual
        DNS requests. See http://cr.yp.to/djbdns/axfr-notes.html for
        more information.
        """
        address = self.pickServer()
        if address is None:
            return defer.fail(IOError('No domain name servers available'))
        host, port = address
        d = defer.Deferred()
        controller = AXFRController(name, d)
        factory = DNSClientFactory(controller, timeout)
        factory.noisy = False #stfu

        from twisted.internet import reactor
        connector = reactor.connectTCP(host, port, factory)
        controller.timeoutCall = reactor.callLater(timeout or 10,
                                                   self._timeoutZone,
                                                   d, controller,
                                                   connector,
                                                   timeout or 10)
        return d.addCallback(self._cbLookupZone, connector)
p2p.py 文件源码 项目:p2pool-ltc 作者: ilsawa 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _think(self):
        try:
            if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
                (host, port), = self.node.get_good_peers(1)

                if self._host_to_ident(host) in self.attempts:
                    pass
                elif host in self.node.bans and self.node.bans[host] > time.time():
                    pass
                else:
                    #print 'Trying to connect to', host, port
                    reactor.connectTCP(host, port, self, timeout=5)
        except:
            log.err()

        return random.expovariate(1/1)
p2p.py 文件源码 项目:p2pool-bsty 作者: amarian12 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _think(self):
        try:
            if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
                (host, port), = self.node.get_good_peers(1)

                if self._host_to_ident(host) in self.attempts:
                    pass
                elif host in self.node.bans and self.node.bans[host] > time.time():
                    pass
                else:
                    #print 'Trying to connect to', host, port
                    reactor.connectTCP(host, port, self, timeout=5)
        except:
            log.err()

        return random.expovariate(1/1)
git_buildbot.py 文件源码 项目:buildbot-contrib 作者: buildbot 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def send_changes():
    # Submit the changes, if any
    if not changes:
        logging.warning("No changes found")
        return

    host, port = master.split(':')
    port = int(port)

    f = pb.PBClientFactory()
    d = f.login(credentials.UsernamePassword(username, auth))
    reactor.connectTCP(host, port, f)

    d.addErrback(connectFailed)
    d.addCallback(connected)
    d.addBoth(cleanup)

    reactor.run()
github_buildbot.py 文件源码 项目:buildbot-contrib 作者: buildbot 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def send_changes(self, changes, request):
        """
        Submit the changes, if any
        """
        if not changes:
            logging.warning("No changes found")
            request.setResponseCode(OK)
            request.write(json.dumps({"result": "No changes found."}))
            request.finish()
            return

        host, port = self.master.split(':')
        port = int(port)

        if self.auth is not None:
            auth = credentials.UsernamePassword(*self.auth.split(":"))
        else:
            auth = credentials.Anonymous()

        factory = pb.PBClientFactory()
        deferred = factory.login(auth)
        reactor.connectTCP(host, port, factory)
        deferred.addErrback(self.connectFailed, request)
        deferred.addCallback(self.connected, changes, request)
p2p.py 文件源码 项目:p2pool-cann 作者: ilsawa 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _think(self):
        try:
            if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
                (host, port), = self.node.get_good_peers(1)

                if self._host_to_ident(host) in self.attempts:
                    pass
                elif host in self.node.bans and self.node.bans[host] > time.time():
                    pass
                else:
                    #print 'Trying to connect to', host, port
                    reactor.connectTCP(host, port, self, timeout=5)
        except:
            log.err()

        return random.expovariate(1/1)
CCcamInfo.py 文件源码 项目:enigma2 作者: BlackHole 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def getPage(url, contextFactory=None, *args, **kwargs):
    scheme, host, port, path, username, password = _parse(url)

    if username and password:
        url = scheme + '://' + host + ':' + str(port) + path
        basicAuth = encodestring("%s:%s" % (username, password))
        authHeader = "Basic " + basicAuth.strip()
        AuthHeaders = {"Authorization": authHeader}

        if kwargs.has_key("headers"):
            kwargs["headers"].update(AuthHeaders)
        else:
            kwargs["headers"] = AuthHeaders

    factory = HTTPClientFactory(url, *args, **kwargs)
    reactor.connectTCP(host, port, factory)

    return factory.deferred

#############################################################
spider_gt.py 文件源码 项目:data007 作者: mobishift2011 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def getPagePrxoy(url, proxy=None, contextFactory=None,
                       *args, **kwargs):
    '''
    proxy=
    {
    host:192.168.1.111,
    port:6666
    }
    '''
    kwargs["timeout"] = 60
    if proxy is None:
        scheme, host, port, path = client._parse(url)
        factory = client.HTTPClientFactory(url, *args, **kwargs)
        if scheme == b'https':
            from twisted.internet import ssl
            if contextFactory is None:
                contextFactory = ssl.ClientContextFactory()
            reactor.connectSSL(client.nativeString(host), port, factory, contextFactory)
        else:
            reactor.connectTCP(client.nativeString(host), port, factory)
        return factory.deferred
    else:
        factory = client.HTTPClientFactory(url, *args, **kwargs)
        reactor.connectTCP(proxy["host"], proxy["port"], factory)
        return factory.deferred
timeout_manager.py 文件源码 项目:DistributedMNIST 作者: agnusmaximus 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, tf_flags):
    self.tf_flags = tf_flags
    self.worker_id = self.tf_flags.task_id
    hosts = self.tf_flags.worker_hosts.split(",")
    hosts = [x.split(":")[0] for x in hosts]
    self.hosts = hosts
    self.self_perspective = None
    self.perspectives = []
    self.ready = False
    self.servers_ready = set([])

    for i, host in enumerate(hosts):
      #factory = pb.PBClientFactory()
      factory = TimeoutReconnectClientFactory()
      tf.logging.info("Connecting to %s:%d" % (host, self.tf_flags.rpc_port))
      reactor.connectTCP(host, self.tf_flags.rpc_port, factory)
      if i == self.worker_id:
        factory.getRootObject().addCallback(self.connected_self)
        #factory.getRootObject().addCallbacks(self.connected_self, self.connect_failure, errbackArgs=[host], errbackKeywords=[])
      else:
        factory.getRootObject().addCallback(self.connected)
        #factory.getRootObject().addCallbacks(self.connected, self.connect_failure, errbackArgs=[host], errbackKeywords=[])
distrib.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET
protocol.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _connect(self, method, *args, **kwargs):
        """
        Initiate a connection attempt.

        @param method: A callable which will actually start the connection
            attempt.  For example, C{reactor.connectTCP}.

        @param *args: Positional arguments to pass to C{method}, excluding the
            factory.

        @param **kwargs: Keyword arguments to pass to C{method}.

        @return: A L{Deferred} which fires with an instance of the protocol
            class passed to this L{ClientCreator}'s initializer or fails if the
            connection cannot be set up for some reason.
        """
        def cancelConnect(deferred):
            connector.disconnect()
            if f.pending is not None:
                f.pending.cancel()
        d = defer.Deferred(cancelConnect)
        f = _InstanceFactory(
            self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
        connector = method(factory=f, *args, **kwargs)
        return d
test_tcp.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_serverRepr(self):
        """
        Check that the repr string of the server transport get the good port
        number if the server listens on 0.
        """
        server = MyServerFactory()
        serverConnMade = server.protocolConnectionMade = defer.Deferred()
        port = reactor.listenTCP(0, server)
        self.addCleanup(port.stopListening)

        client = MyClientFactory()
        clientConnMade = client.protocolConnectionMade = defer.Deferred()
        connector = reactor.connectTCP("127.0.0.1",
                                       port.getHost().port, client)
        self.addCleanup(connector.disconnect)
        def check(result):
            serverProto, clientProto = result
            portNumber = port.getHost().port
            self.assertEqual(
                repr(serverProto.transport),
                "<AccumulatingProtocol #0 on %s>" % (portNumber,))
            serverProto.transport.loseConnection()
            clientProto.transport.loseConnection()
        return defer.gatherResults([serverConnMade, clientConnMade]
            ).addCallback(check)
twistedreactor.py 文件源码 项目:deb-python-cassandra-driver 作者: openstack 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def add_connection(self):
        """
        Convenience function to connect and store the resulting
        connector.
        """
        self.connector = reactor.connectTCP(
            host=self.host, port=self.port,
            factory=TwistedConnectionClientFactory(self),
            timeout=self.connect_timeout)
recipe-473865.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def callRemote(self, method, *args):
        factory = AuthQueryFactory(self.url, method, *args)
        if self.secure:
            from twisted.internet import ssl
            reactor.connectSSL(self.host, self.port or 443,
                               factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.host, self.port or 80, factory)
        return factory.deferred
recipe-286201.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _doConnect(self, tp, server, port):
        d = Deferred()
        self.factory = ChatClientFactory(d, tp, self.onConnectionMade)
        self.connector = reactor.connectTCP(server, int(port), self.factory)
        return d
portforward.py 文件源码 项目:darkc0de-old-stuff 作者: tuwid 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def connectionMade(self):
    self.serverName="%s:%d" %(self.factory.remote_host,self.factory.remote_port)
    logger.info("client %s opened connection -> server %s" % (
      self.clientName, self.serverName))

    # cxn to this server has opened. Open a port to the destination...
    reactor.connectTCP(self.factory.remote_host,
      self.factory.remote_port, self.clientFactory)


问题


面经


文章

微信
公众号

扫码关注公众号