当前位置: 首页>>代码示例>>Python>>正文


Python endpoints.connectProtocol函数代码示例

本文整理汇总了Python中twisted.internet.endpoints.connectProtocol函数的典型用法代码示例。如果您正苦于以下问题:Python connectProtocol函数的具体用法?Python connectProtocol怎么用?Python connectProtocol使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了connectProtocol函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process

    def process(self):
        parsed = urllib_parse.urlparse(self.uri)
        protocol = parsed[0]
        host = parsed[1].decode('ascii')
        if protocol in self.ports:
            port = self.ports[protocol]
        else:
            # handle
            pass

        if ':' in host:
            host, port = host.split(':')
            port = int(port)
        rest = urllib_parse.urlunparse((b'', b'') + parsed[2:])
        if not rest:
            rest = rest + b'/'
        
        if protocol in self.protocols:
            factory = self.protocols[protocol]
            headers = self.getAllHeaders().copy()
            if b'host' not in headers:
                headers[b'host'] = host.encode('ascii')
                
            headers.pop(b'user-agent', None)
            headers[b'user-agent'] = b'I2P'
        
        
            self.content.seek(0, 0)
            s = self.content.read()
            client = factory(self.method, rest, self.clientproto, headers, s, self)
            ep = self.endpointFactory(host, port)
            connectProtocol(ep, client.buildProtocol(ep))
开发者ID:majestrate,项目名称:i2p-tools,代码行数:32,代码来源:http.py

示例2: doMath

def doMath():
    destination = TCP4ClientEndpoint(reactor, "127.0.0.1", 1234)
    sumDeferred = connectProtocol(destination, AMP())

    def connected(ampProto):
        return ampProto.callRemote(Sum, a=13, b=81)

    sumDeferred.addCallback(connected)

    def summed(result):
        return result["total"]

    sumDeferred.addCallback(summed)

    divideDeferred = connectProtocol(destination, AMP())

    def connected(ampProto):
        return ampProto.callRemote(Divide, numerator=1234, denominator=0)

    divideDeferred.addCallback(connected)

    def trapZero(result):
        result.trap(ZeroDivisionError)
        print "Divided by zero: returning INF"
        return 1e1000

    divideDeferred.addErrback(trapZero)

    def done(result):
        print "Done with math:", result
        reactor.stop()

    defer.DeferredList([sumDeferred, divideDeferred]).addCallback(done)
开发者ID:samsoft00,项目名称:careervacancy,代码行数:33,代码来源:ampclient.py

示例3: test_basic

    def test_basic(self):
        ep = clientFromString(reactor, self.transit)
        a1 = yield connectProtocol(ep, Accumulator())
        a2 = yield connectProtocol(ep, Accumulator())

        token1 = b"\x00"*32
        a1.transport.write(b"please relay " + hexlify(token1) + b"\n")
        a2.transport.write(b"please relay " + hexlify(token1) + b"\n")

        # a correct handshake yields an ack, after which we can send
        exp = b"ok\n"
        yield a1.waitForBytes(len(exp))
        self.assertEqual(a1.data, exp)
        s1 = b"data1"
        a1.transport.write(s1)

        exp = b"ok\n"
        yield a2.waitForBytes(len(exp))
        self.assertEqual(a2.data, exp)

        # all data they sent after the handshake should be given to us
        exp = b"ok\n"+s1
        yield a2.waitForBytes(len(exp))
        self.assertEqual(a2.data, exp)

        a1.transport.loseConnection()
        a2.transport.loseConnection()
开发者ID:dreid,项目名称:magic-wormhole,代码行数:27,代码来源:test_server.py

示例4: range_check

    def range_check(self, firstbyte, lastbyte, setset=False):
        test_deferred = Deferred()
        self._logger.debug("range_test: %s %s %s setset %s", firstbyte, lastbyte, self.sourcesize, setset)

        if firstbyte is not None and lastbyte is None:
            exp_byte_range = (firstbyte, self.sourcesize - 1)
        elif firstbyte is None and lastbyte is not None:
            exp_byte_range = (self.sourcesize - lastbyte, self.sourcesize - 1)
        else:
            exp_byte_range = (firstbyte, lastbyte)

        # the amount of bytes actually requested. (Content-length)
        self.expsize = exp_byte_range[1] - exp_byte_range[0] + 1
        f = open(self.sourcefn, "rb")
        f.seek(exp_byte_range[0])

        expdata = f.read(self.expsize)
        f.close()

        def on_connected(p):
            p.sendMessage(self.get_header(firstbyte, lastbyte, setset))

        endpoint = TCP4ClientEndpoint(reactor, "localhost", self.port)
        connectProtocol(endpoint, VideoServerProtocol(test_deferred, self.sourcesize, expdata, setset, exp_byte_range))\
            .addCallback(on_connected)
        return test_deferred
开发者ID:synctext,项目名称:tribler,代码行数:26,代码来源:test_video_server.py

示例5: on_deploy_start

    def on_deploy_start(self):
        now = int(time.time())
        events = ("events.deploy.%s %d %d\r\n" % (component, 1, now)
                  for component in self.components)
        message = "".join(events)
        protocol = OneShotMessageWriter(message)

        endpoint = endpoints.clientFromString(reactor, self.endpoint_config)
        endpoints.connectProtocol(endpoint, protocol)
开发者ID:dellis23,项目名称:rollingpin,代码行数:9,代码来源:graphite.py

示例6: start_client

 def start_client(proto):
     client_endpoint = TCP4ClientEndpoint(reactor, 'localhost', 1234)
     nickname = 'PyClient' + str(random.getrandbits(23))
     factory = PyClientProtocolFactory(nickname)
     proto = factory.buildProtocol(('localhost', 0))
     connectProtocol(client_endpoint, proto)
     d = Deferred()
     reactor.callLater(4, d.callback, proto)
     d.addCallback(test_state)
     return d
开发者ID:FlorianWilhelm,项目名称:pokerthproto,代码行数:10,代码来源:test_proxy.py

示例7: connectionMade

 def connectionMade(self):
     script_dir = os.getcwd()
     rel_path = "hostkeys"
     abs_file_path = os.path.join(script_dir, rel_path)
     knownHosts = KnownHostsFile.fromPath(abs_file_path)
     self.point = SSHCommandClientEndpoint.newConnection(reactor, 'cmd', 'user', '127.0.0.1', port=5122,
                                                         password='password', knownHosts=PermissiveKnownHosts())
     self.sshSide = FzSSHClient()
     self.sshSide.tcpSide = self
     connectProtocol(self.point, self.sshSide)
开发者ID:matanmaz,项目名称:SshTelnetProxy,代码行数:10,代码来源:TcpSshConverter.py

示例8: perform_run

 def perform_run(dispatcher, intent):
     context.bind(
         message_type="flocker.provision.ssh:run",
         command=intent.log_command_filter(intent.command),
     ).write()
     endpoint = SSHCommandClientEndpoint.existingConnection(
         connection, intent.command)
     d = Deferred()
     connectProtocol(endpoint, CommandProtocol(
         deferred=d, context=context))
     return d
开发者ID:wangbinxiang,项目名称:flocker,代码行数:11,代码来源:_conch.py

示例9: onEvent

 def onEvent(self, ev):
     if ev.getName() == YowNetworkLayer.EVENT_STATE_CONNECT:
         # self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
         # self.out_buffer = bytearray()
         endpoint = self.getProp(YowNetworkLayer.PROP_ENDPOINT)
         point = TCP4ClientEndpoint(reactor, endpoint[0], endpoint[1])
         connectProtocol(point, self)
         # self.connect(endpoint)
         return True
     elif ev.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECT:
         self.handle_close(ev.getArg("reason") or "Requested")
         return True
开发者ID:a-d-j-i,项目名称:yowsup,代码行数:12,代码来源:layer.py

示例10: _connectServer

    def _connectServer(self, hostname, port, server_queue, client_queue):
        """A helper function for connecting to (hostname, port)
        with the given server and client queues.

        :param str hostname:
        :param int port:
        :param DeferredQueue server_queue:
        :param DeferredQueue client_queue:
        """
        endpoint = TCP4ClientEndpoint(reactor, hostname, port)
        protocol = ServerProtocol(
            server_queue, client_queue)
        connectProtocol(endpoint, protocol)
开发者ID:naphatkrit,项目名称:TigerHost,代码行数:13,代码来源:spoof_tcp_proxy.py

示例11: run

def run(messagehandler): 

    options = optionsForClientTLS(
        hostname=AUTHORITY,
        acceptableProtocols=[b'h2', b'http/1.1'],
    )

    connectProtocol(
        SSL4ClientEndpoint(reactor, AUTHORITY, 443, options),
        H2Protocol(messagehandler)
    )

    reactor.run(installSignalHandlers=0)
开发者ID:pbsugg,项目名称:http2-frame-visualizer,代码行数:13,代码来源:twisted_runner.py

示例12: connectServer

    def connectServer(self, hostname, port):
        """Tell the proxy what the end server is and start the connection.

        The messages in `self.client_queue` will automatically be consumed.

        This method should only be called once.

        :param str hostname:
        :param int port:
        """
        endpoint = TCP4ClientEndpoint(reactor, hostname, port)
        protocol = ServerProtocol(
            self.server_queue, self.client_queue)
        connectProtocol(endpoint, protocol)
开发者ID:naphatkrit,项目名称:TigerHost,代码行数:14,代码来源:tcp_proxy.py

示例13: main

def main(reactor=reactor):
    arguments = vars(parser.parse_args())
    endpoint = clientFromString(
        reactor=reactor,
        description=arguments["endpoint"],
    )

    lines = iter(replay_file(arguments["queries"]))

    client = BenchmarkClient()
    client.lineiterator = lines
    connectProtocol(endpoint, client).addCallback(
        lambda protocol : protocol.sendLine(lines.next()),
    )
    reactor.run()
开发者ID:smartkiwi,项目名称:HuntingWabbits,代码行数:15,代码来源:client.py

示例14: main

def main(reactor, args):
    endpoint_str = args.endpoint
    e = clientFromString(reactor, endpoint_str)
    d = connectProtocol(e, LDAPClient())
    d.addCallback(onConnect, args)
    d.addErrback(onError)
    return d
开发者ID:GrayAn,项目名称:ldaptor,代码行数:7,代码来源:client_paged_search_results.py

示例15: run

def run(reactor, command, **kwargs):
    """
    Run a process and kill it if the reactor stops.

    :param reactor: Reactor to use.
    :param list command: The command to run.

    :return Deferred: Deferred that fires when the process is ended.
    """
    if 'env' not in kwargs:
        kwargs['env'] = os.environ
    endpoint = ProcessEndpoint(reactor, command[0], command, **kwargs)
    protocol_done = Deferred()
    protocol = CommandProtocol(deferred=protocol_done, output=sys.stdout)

    connected = connectProtocol(endpoint, protocol)

    def unregister_killer(result, trigger_id):
        try:
            reactor.removeSystemEventTrigger(trigger_id)
        except:
            # If we can't remove the trigger, presumably it has already been
            # removed (or run). In any case, there is nothing sensible to do
            # if this fails.
            pass
        return result

    def register_killer(_):
        trigger_id = reactor.addSystemEventTrigger(
            'before', 'shutdown', protocol.transport.signalProcess, 'TERM')
        protocol_done.addBoth(unregister_killer, trigger_id)

    connected.addCallback(register_killer)
    connected.addCallback(lambda _: protocol_done)
    return connected
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:35,代码来源:runner.py


注:本文中的twisted.internet.endpoints.connectProtocol函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。