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


Python ServerFactory.protocol方法代码示例

本文整理汇总了Python中twisted.internet.protocol.ServerFactory.protocol方法的典型用法代码示例。如果您正苦于以下问题:Python ServerFactory.protocol方法的具体用法?Python ServerFactory.protocol怎么用?Python ServerFactory.protocol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.protocol.ServerFactory的用法示例。


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

示例1: manhole_factory

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def manhole_factory(namespace, username, password):
    """
    Produces a factory object which can be used to listen for telnet
    connections to the manhole.
    """
    assert isinstance(namespace, dict)
    assert isinstance(username, STRING_TYPES)
    assert isinstance(password, STRING_TYPES)
    assert TelnetRealm.NAMESPACE is None, "namespace already set"

    # TODO: we should try to use the system to authorize users instead
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(username, password)

    # Setup the namespace
    namespace = namespace.copy()
    namespace.setdefault("pp", pprint)
    namespace.setdefault("show", show)

    realm = TelnetRealm()
    TelnetRealm.NAMESPACE = namespace
    portal = Portal(realm, [checker])
    factory = ServerFactory()
    factory.protocol = TransportProtocolFactory(portal)
    return factory
开发者ID:xlhtc007,项目名称:pyfarm-agent,代码行数:27,代码来源:manhole.py

示例2: test_addresses

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
    def test_addresses(self):
        """
        A client's transport's C{getHost} and C{getPeer} return L{IPv4Address}
        instances which give the dotted-quad string form of the local and
        remote endpoints of the connection respectively.
        """
        host, port = self._freePort()
        reactor = self.buildReactor()

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol
        server = reactor.listenTCP(0, serverFactory, interface=host)
        serverAddress = server.getHost()

        addresses = {"host": None, "peer": None}

        class CheckAddress(Protocol):
            def makeConnection(self, transport):
                addresses["host"] = transport.getHost()
                addresses["peer"] = transport.getPeer()
                reactor.stop()

        clientFactory = Stop(reactor)
        clientFactory.protocol = CheckAddress
        client = reactor.connectTCP("localhost", server.getHost().port, clientFactory, bindAddress=("127.0.0.1", port))

        reactor.installResolver(FakeResolver({"localhost": "127.0.0.1"}))
        reactor.run()  # self.runReactor(reactor)

        self.assertEqual(addresses["host"], IPv4Address("TCP", "127.0.0.1", port))
        self.assertEqual(addresses["peer"], IPv4Address("TCP", "127.0.0.1", serverAddress.port))
开发者ID:Berimor66,项目名称:mythbox,代码行数:33,代码来源:test_tcp.py

示例3: createBaseService

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def createBaseService(options):
    root_service = RurouniRootService()
    root_service.setName('rurouni')

    receive_services = (
        (settings.LINE_RECEIVER_INTERFACE,
         settings.LINE_RECEIVER_PORT,
         protocols.MetricLineReceiver
        ),
        (settings.PICKLE_RECEIVER_INTERFACE,
         settings.PICKLE_RECEIVER_PORT,
         protocols.MetricPickleReceiver
        ),
    )
    for interface, port, protocol in receive_services:
        if port:
            factory = ServerFactory()
            factory.protocol = protocol
            service = TCPServer(int(port), factory, interface=interface)
            service.setServiceParent(root_service)

    from rurouni.state.instrumentation import InstrumentationService
    service = InstrumentationService()
    service.setServiceParent(root_service)

    return root_service
开发者ID:douban,项目名称:Kenshin,代码行数:28,代码来源:service.py

示例4: test_connectEvent

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
    def test_connectEvent(self):
        """
        This test checks that we correctly get notifications event for a
        client. This ought to prevent a regression under Windows using the GTK2
        reactor. See #3925.
        """
        reactor = self.buildReactor()

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol
        server = reactor.listenTCP(0, serverFactory)
        connected = []

        class CheckConnection(Protocol):
            def connectionMade(self):
                connected.append(self)
                reactor.stop()

        clientFactory = Stop(reactor)
        clientFactory.protocol = CheckConnection
        client = reactor.connectTCP("127.0.0.1", server.getHost().port, clientFactory)

        reactor.run()

        self.assertTrue(connected)
开发者ID:Berimor66,项目名称:mythbox,代码行数:27,代码来源:test_tcp.py

示例5: createCacheService

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def createCacheService(config):
    from carbon.cache import MetricCache
    from carbon.conf import settings
    from carbon.protocols import CacheManagementHandler

    # Configure application components
    events.metricReceived.addHandler(MetricCache.store)

    root_service = createBaseService(config)
    factory = ServerFactory()
    factory.protocol = CacheManagementHandler
    service = TCPServer(int(settings.CACHE_QUERY_PORT), factory,
                        interface=settings.CACHE_QUERY_INTERFACE)
    service.setServiceParent(root_service)

    # have to import this *after* settings are defined
    from carbon.writer import WriterService

    service = WriterService()
    service.setServiceParent(root_service)

    if settings.USE_FLOW_CONTROL:
      events.cacheFull.addHandler(events.pauseReceivingMetrics)
      events.cacheSpaceAvailable.addHandler(events.resumeReceivingMetrics)

    return root_service
开发者ID:laiwei,项目名称:carbon,代码行数:28,代码来源:service.py

示例6: makeService

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def makeService(config):
    s = appservice.MultiService()
    conf = inetdconf.InetdConf()
    conf.parseFile(open(config['file']))

    for service in conf.services:
        protocol = service.protocol

        if service.protocol.startswith('rpc/'):
            log.msg('Skipping rpc service due to lack of rpc support')
            continue

        if (protocol, service.socketType) not in [('tcp', 'stream'),
                                                  ('udp', 'dgram')]:
            log.msg('Skipping unsupported type/protocol: %s/%s'
                    % (service.socketType, service.protocol))
            continue

        # Convert the username into a uid (if necessary)
        try:
            service.user = int(service.user)
        except ValueError:
            try:
                service.user = pwd.getpwnam(service.user)[2]
            except KeyError:
                log.msg('Unknown user: ' + service.user)
                continue

        # Convert the group name into a gid (if necessary)
        if service.group is None:
            # If no group was specified, use the user's primary group
            service.group = pwd.getpwuid(service.user)[3]
        else:
            try:
                service.group = int(service.group)
            except ValueError:
                try:
                    service.group = grp.getgrnam(service.group)[2]
                except KeyError:
                    log.msg('Unknown group: ' + service.group)
                    continue

        if service.program == 'internal':
            if config['nointernal']:
                continue

            # Internal services can use a standard ServerFactory
            if service.name not in inetd.internalProtocols:
                log.msg('Unknown internal service: ' + service.name)
                continue
            factory = ServerFactory()
            factory.protocol = inetd.internalProtocols[service.name]
        else:
            factory = inetd.InetdFactory(service)

        if protocol == 'tcp':
            internet.TCPServer(service.port, factory).setServiceParent(s)
        elif protocol == 'udp':
            raise RuntimeError("not supporting UDP")
    return s
开发者ID:BarnetteME1,项目名称:indeed_scraper,代码行数:62,代码来源:inetdtap.py

示例7: start

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def start(_settings, _backend, telnet_port=8023):
    """
    Start telnet server
    """
    global settings
    global backend
    backend = _backend

    # Settings
    settings = _settings()

    # Thread sensitive interface for stdout/stdin
    std.setup()

    # Telnet
    telnet_factory = ServerFactory()
    telnet_factory.protocol = lambda: TelnetTransport(TelnetDeployer)

    # Handle signals
    def handle_sigint(signal, frame):
        if active_sessions:
            print 'Running, %i active session(s).' % len(active_sessions)
        else:
            print 'No active sessions, exiting'
            reactor.stop()

    signal.signal(signal.SIGINT, handle_sigint)

    # Run the reactor!
    print 'Listening telnet on localhost:%s...' % telnet_port

    reactor.listenTCP(telnet_port, telnet_factory)
    reactor.run()
开发者ID:aitzol,项目名称:python-deployer,代码行数:35,代码来源:__init__.py

示例8: _serverGetConnectionAddressTest

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
    def _serverGetConnectionAddressTest(self, client, interface, which):
        """
        Connect C{client} to a server listening on C{interface} started with
        L{IReactorTCP.listenTCP} and return the address returned by one of the
        server transport's address lookup methods, C{getHost} or C{getPeer}.

        @param client: A C{SOCK_STREAM} L{socket.socket} created with an address
            family such that it will be able to connect to a server listening on
            C{interface}.

        @param interface: A C{str} giving an address for a server to listen on.
            This should almost certainly be the loopback address for some
            address family supported by L{IReactorTCP.listenTCP}.

        @param which: A C{str} equal to either C{"getHost"} or C{"getPeer"}
            determining which address will be returned.

        @return: Whatever object, probably an L{IAddress} provider, is returned
            from the method indicated by C{which}.
        """
        class ObserveAddress(Protocol):
            def makeConnection(self, transport):
                reactor.stop()
                self.factory.address = getattr(transport, which)()

        reactor = self.buildReactor()
        factory = ServerFactory()
        factory.protocol = ObserveAddress
        port = reactor.listenTCP(0, factory, interface=interface)
        client.setblocking(False)
        try:
            client.connect((port.getHost().host, port.getHost().port))
        except socket.error, (errnum, message):
            self.assertIn(errnum, (errno.EINPROGRESS, errno.EWOULDBLOCK))
开发者ID:antong,项目名称:twisted,代码行数:36,代码来源:test_tcp.py

示例9: makeService

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def makeService(options):
    # primary setup
    application = service.Application(meta.display_name)
    services = service.IServiceCollection(application)

    # setup message server
    serverFactory = ServerFactory()
    serverFactory.protocol = Listener
    serverFactory.publisher = PublisherFactory()

    msgServer = internet.TCPServer(config.listener.port, serverFactory)
    msgServer.setName(config.listener.servicename)
    msgServer.setServiceParent(services)

    # setup IRC message client
    if config.irc.sslEnabled:
        msgService = internet.SSLClient(config.irc.server, config.irc.port,
            serverFactory.publisher, ClientContextFactory())
    else:
        msgService = internet.TCPClient(config.irc.server, config.irc.port,
            serverFactory.publisher)
    msgService.setName(config.irc.servicename)
    msgService.setServiceParent(services)

    # setup IRC log client
    logger = LoggerFactory(config.irc.server, config.log.channels)
    logService = internet.TCPClient(config.irc.server, config.irc.port,
        logger)
    logService.setName(config.log.servicename)
    logService.setServiceParent(services)

    # setuplog rotator
    rotService = internet.TimerService(config.log.rotate.checkInterval,
        logger.rotateLogs, logService)
    rotService.setName(config.log.rotate.servicename)
    rotService.setServiceParent(services)

    # setup log file web server
    webroot = static.File(config.log.http.docRoot)
    if config.log.http.vhostEnabled:
        vResource = vhost.VHostMonsterResource()
        webroot.putChild('vhost', vResource)
    if config.log.http.auth == 'basic':
        guarded = auth.guardResourceWithBasicAuth(
            webroot, config.log.http.realm, config.log.http.users)
        site = server.Site(guarded)
    else:
        site = server.Site(webroot)
    webserver = internet.TCPServer(config.log.http.port, site)
    webserver.setName(config.log.http.servicename)
    webserver.setServiceParent(services)

    # setup ssh access to a Python shell
    interpreterType = carapace_const.PYTHON
    sshFactory = getShellFactory(
        interpreterType, app=application, services=services)
    sshserver = internet.TCPServer(config.ssh.port, sshFactory)
    sshserver.setName(config.ssh.servicename)
    sshserver.setServiceParent(services)
    return services
开发者ID:oubiwann,项目名称:bot-prakasha-ke,代码行数:62,代码来源:service.py

示例10: get_service

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
 def get_service(self):
     factory = ServerFactory()
     factory.protocol = SimpleTelnetSession
     factory.game = self.game
     service = internet.TCPServer(self.options.getint('port'), factory)
     service.setName("SimpleTelnetServer")
     return service
开发者ID:joshbenner,项目名称:mudsling,代码行数:9,代码来源:__init__.py

示例11: main

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def main():
    global world
    tornado.options.parse_command_line()

    # configure logging
    log_level = logging.DEBUG if options.debug else logging.INFO
    logging.basicConfig(level=log_level)

    # init world singleton
    world_module = import_module(options.world)
    world = World(world_module.world)

    # configure the Telnet server
    factory = ServerFactory()
    factory.protocol = MudTelnetProtocol
    reactor.listenTCP(options.telnetport, factory)

    # init Tornado app
    app = Application()
    app.listen(options.port)

    # configure tick interrupt
    ticker = tornado.ioloop.PeriodicCallback(world.tick, options.tick * 1000)
    ticker.start()

    # configure admin debug server
    reactor.listenTCP(2222, getManholeFactory(globals(), admin='admin'))

    # start the server(s)
    logging.info("Listening on port %d" % options.port)
    tornado.ioloop.IOLoop.instance().start()
开发者ID:trentonstrong,项目名称:easymud,代码行数:33,代码来源:server.py

示例12: main

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def main():

    factory = ServerFactory()
    factory.clients = {}
    factory.protocol = myFactory
    reactor.listenTCP(8000,factory)
    reactor.run()
开发者ID:JordanBlocher,项目名称:SandBox,代码行数:9,代码来源:factory.py

示例13: test_writeSequence

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
    def test_writeSequence(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are
        received by the protocol on the other side of the connection.
        """
        bytes = "some bytes"
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.writeSequence(list(bytes))

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred
开发者ID:Almad,项目名称:twisted,代码行数:37,代码来源:test_tls.py

示例14: main

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def main():
    # Initialize log
    log.Log.getInstance(sys.stdout)

    for protocol in (
        Drop,
        ReadAndDrop,
        GarbageStatus,
        BadHeader,
        PauseHeader,
        Redirect,
        DataDrop,
        DropOnce,
        NoCR,
        PipeDrop,
        RedirectLoop,
        ReadAll,
        Timeout,
        SlowResponse,
    ):
        factory = ServerFactory()
        factory.protocol = protocol
        reactor.listenTCP(protocol.PORT, factory)

    reactor.run()
开发者ID:XUbiker,项目名称:platform_development,代码行数:27,代码来源:axl.py

示例15: setupReceivers

# 需要导入模块: from twisted.internet.protocol import ServerFactory [as 别名]
# 或者: from twisted.internet.protocol.ServerFactory import protocol [as 别名]
def setupReceivers(root_service, settings):
  from carbon.protocols import MetricLineReceiver, MetricPickleReceiver, MetricDatagramReceiver

  for protocol, interface, port in [
      (MetricLineReceiver, settings.LINE_RECEIVER_INTERFACE, settings.LINE_RECEIVER_PORT),
      (MetricPickleReceiver, settings.PICKLE_RECEIVER_INTERFACE, settings.PICKLE_RECEIVER_PORT)
    ]:
    if port:
      factory = ServerFactory()
      factory.protocol = protocol
      service = TCPServer(port, factory, interface=interface)
      service.setServiceParent(root_service)

  if settings.ENABLE_UDP_LISTENER:
      service = UDPServer(int(settings.UDP_RECEIVER_PORT),
                          MetricDatagramReceiver(),
                          interface=settings.UDP_RECEIVER_INTERFACE)
      service.setServiceParent(root_service)

  if settings.ENABLE_AMQP:
    from carbon import amqp_listener
    amqp_host = settings.AMQP_HOST
    amqp_port = settings.AMQP_PORT
    amqp_user = settings.AMQP_USER
    amqp_password = settings.AMQP_PASSWORD
    amqp_verbose = settings.AMQP_VERBOSE
    amqp_vhost = settings.AMQP_VHOST
    amqp_spec = settings.AMQP_SPEC
    amqp_exchange_name = settings.AMQP_EXCHANGE

    factory = amqp_listener.createAMQPListener(
      amqp_user,
      amqp_password,
      vhost=amqp_vhost,
      spec=amqp_spec,
      exchange_name=amqp_exchange_name,
      verbose=amqp_verbose)
    service = TCPClient(amqp_host, amqp_port, factory)
    service.setServiceParent(root_service)

  if settings.ENABLE_MANHOLE:
    from carbon import manhole

    # Configure application components
    if settings.RELAY_METHOD == 'rules':
      router = RelayRulesRouter(settings["relay-rules"])
    elif settings.RELAY_METHOD == 'consistent-hashing':
      router = ConsistentHashingRouter(settings.REPLICATION_FACTOR)
    elif settings.RELAY_METHOD == 'aggregated-consistent-hashing':
      from carbon.aggregator.rules import RuleManager
      RuleManager.read_from(settings["aggregation-rules"])
      router = AggregatedConsistentHashingRouter(RuleManager, settings.REPLICATION_FACTOR)
    elif settings.RELAY_METHOD == 'remove-node-consistent-hashing':
      router = RemoveNodeConsistentHashingRouter(settings.REPLICATION_FACTOR, settings.REMOVE_NODE_INDEX)
    factory = manhole.createManholeListener()
    service = TCPServer(
      settings.MANHOLE_PORT,
      factory,
      interface=settings.MANHOLE_INTERFACE)
    service.setServiceParent(root_service)
开发者ID:zhpn,项目名称:carbon,代码行数:62,代码来源:service.py


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