• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python reactor.listenTCP函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __init__

	def __init__(self, password = None, port = 9000):
		'''
		Creates and Agent instance and attemps to connect
		to the AgentMaster.  If connection works the Client Hello message
		is sent.
		
		@type	password: string
		@param	password: Password to use
		'''
		
		from twisted.internet import reactor
		agent = AgentXmlRpc()
		
		agent._password = password
		agent._monitors = []
		agent._publishers = {}
		agent._id = None
		
		print "] Peach Agent\n"
		
		if agent._password != None:
			print "\n //-> Listening on [%s] with password [%s]\n" % (port, agent._password)
		else:
			print "\n //-> Listening on [%s] with no password\n" % (port)
		
		reactor.listenTCP(port, server.Site(agent))
		reactor.run()
开发者ID:flaub,项目名称:HotFuzz,代码行数:27,代码来源:agent.py


示例2: main

def main():
	factory = protocol.ServerFactory()      # 实例化一个ServerFactory对象
	factory.protocol = Echo     # 重写protocol

	# reactor(反应堆)就是twisted的事件驱动,是twisted的核心.
	reactor.listenTCP(1234, factory)  # 将factory回调函数注册到reactor中,reactor监听指定端口,根据状态来触发factory中不同的方法
	reactor.run()   # 启动一个TCP服务器, 监听1234端口,reactor则开始监听。
开发者ID:chenjinpeng1,项目名称:S12,代码行数:7,代码来源:twisted_echo_server.py


示例3: __init__

 def __init__(self, lm, port=12346, n=0):
     """n indicates the n-gram size, if set to 0 (which is default), the server will expect to only receive whole sentence, if set to a particular value, it will only expect n-grams of that value"""
     if n == 0:
         reactor.listenTCP(port, LMSentenceFactory(lm))
     else:
         reactor.listenTCP(port, LMNGramFactory(lm))
     reactor.run()
开发者ID:493238731,项目名称:pynlpl,代码行数:7,代码来源:server.py


示例4: main

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--port')
  parser.add_argument('--store')
  parser.add_argument('--retrieve')
  parser.add_argument('--connect', default=None)

  args = parser.parse_args()
  port = int(args.port)

  service = ChordService()

  if (args.connect):
    dst = args.connect.split(':')
    service.AddToRoutingTable(IPv4Address('TCP', dst[0], int(dst[1])))

  if (args.store):
    key, value = args.store.split(':')
    service.StoreValue(key, value)
    
  if (args.retrieve):
    def EchoValue(value):
      print('Retrieved value: {}.'.format(value))
    d = service.GetValue(args.retrieve)
    d.addCallback(EchoValue)

  f = pb.PBServerFactory(service)
  reactor.listenTCP(port, f)
    
  reactor.run()
开发者ID:darka,项目名称:p2pfs,代码行数:30,代码来源:chord_node.py


示例5: init_api

 def init_api(self):
     log.msg('Starting HTTP on %s...' % self.interface)
     root = resource.Resource()
     root.putChild("send", APISendResource(self))
     site = server.Site(root, logPath='/dev/null')
     host, port = self.interface.split(':')
     reactor.listenTCP(int(port), site, interface=host)
开发者ID:jackman0925,项目名称:pusher,代码行数:7,代码来源:pusher.py


示例6: main

def main():
    # command line processing
    process_commandline()

    call_list_server = None
    # run the call list providing web server in listening mode
    if CONFIG["LISTEN"]:
        call_list_server = CallListServer()
        site = http_server.Site(call_list_server)
        try:
            reactor.listenTCP(CONFIG["HTTP_PORT"], site, interface=CONFIG["HTTP_HOST"])
        except:
            # port could not be bound
            # (already in use, permission denied, ...)
            call_list_server = None
        else:
            dprint("running call list web server on 'http://{HTTP_HOST}:{HTTP_PORT}'".format(**CONFIG))

    # configure notifications
    enable_notifcations(
        not CONFIG["DISABLE_NOTIFICATIONS"],
        # 'All recent calls...' link only when the call list webserver
        # is running
        call_list_server,
    )

    # start the client
    reactor.connectTCP(
        CONFIG["NCID_HOST"], CONFIG["NCID_PORT"], NCIDClientFactory(reactor, CONFIG["LISTEN"], call_list_server)
    )

    # run the event dispatcher
    reactor.run()

    dprint("done.")
开发者ID:shrick,项目名称:ncidmon,代码行数:35,代码来源:ncidmon.py


示例7: run

def run(create_publisher, host='', port=80):
    """Runs a Twisted HTTP server server that publishes a Quixote
    application."""
    publisher = create_publisher()
    factory = QuixoteFactory(publisher)
    reactor.listenTCP(port, factory, interface=host)
    reactor.run()
开发者ID:pganti,项目名称:micheles,代码行数:7,代码来源:twisted_server.py


示例8: do_listening

def do_listening():
	print "Listening for sensors..."
	reactor.listenTCP(SENSORPORT, SensorFactory())
	try:
		reactor.run(installSignalHandlers=0)
	except ReactorAlreadyRunning, e:
		pass
开发者ID:team-2,项目名称:responsive-rooms,代码行数:7,代码来源:msens.py


示例9: splash_server

def splash_server(portnum, slots, network_manager, get_splash_proxy_factory=None,
                  js_profiles_path=None, disable_proxy=False, proxy_portnum=None):
    from twisted.internet import reactor
    from twisted.web.server import Site
    from splash.resources import Root
    from splash.pool import RenderPool
    from twisted.python import log

    slots = defaults.SLOTS if slots is None else slots
    log.msg("slots=%s" % slots)

    pool = RenderPool(
        slots=slots,
        network_manager=network_manager,
        get_splash_proxy_factory=get_splash_proxy_factory,
        js_profiles_path=js_profiles_path
    )

    # HTTP API
    root = Root(pool)
    factory = Site(root)
    reactor.listenTCP(portnum, factory)

    # HTTP Proxy
    if disable_proxy is False:
        from splash.proxy_server import SplashProxyFactory
        splash_proxy_factory = SplashProxyFactory(pool)
        proxy_portnum = defaults.PROXY_PORT if proxy_portnum is None else proxy_portnum
        reactor.listenTCP(proxy_portnum, splash_proxy_factory)
开发者ID:andresp99999,项目名称:splash,代码行数:29,代码来源:server.py


示例10: init

def init(args):
    # hook events
    if args["--kill"]:
        s_events.gotRequest += kill
    if args["--auth"]:
        s_events.gotRequest += auth
        
    if args["--inject"]:
        c_events.gotResponseTree += inject
    if args["--beef"]:
        c_events.gotResponseTree += beef
    if args["--cats"]:
        c_events.gotResponseTree += cats
        
    if args["--upsidedown"]:
       c_events.gotResponseImage += upsidedown
       
    # start servers
    if args["--cats"] or args["--inject"]:
        datafolder = os.path.join(os.path.dirname(__file__), "data")
        reactor.listenTCP(FILEPORT, fileserver.Site( \
                fileserver.Data(datafolder)))
        log.info("starting file server on %s:%s" %(IP, FILEPORT))
    
    if args["--beef"]:
        Popen(["gnome-terminal", "-e", "./startbeef"])
        log.info("starting beef server on %s" %BEEFPORT)
开发者ID:simonm3,项目名称:mim,代码行数:27,代码来源:otherplugins.py


示例11: startup_routine

 def startup_routine(self):
     indexContent = False
     yes = set(['', 'Y', 'y', 'Yes', 'yes', 'YES'])
     no = set(['N', 'n', 'No', 'no', 'NO'])
     index_on_startup = False
     print("Type 'help' for help.")
     while True:
         print(">> ", end="")
         user_input = str(raw_input())
         if user_input == 'help': # Print available commands to user.
             print()
             print("         <command>   -       <description>")
             print("         help        -       Help.")
             print("         reset       -       Reset index database.")
             print("         init        -       Index all articles from content service on startup.")
             print("         start       -       Start service.")
             print("         exit        -       Quit.")
             print()
         elif user_input == 'reset': # Clearing tables in the index database.
             print("This will delete any existing data and reset the database.")
             print("Are you sure you want to continue? [Y/n] ", end="")
             while True:
                 user_input = str(raw_input())
                 if user_input in yes:
                     self.index_database.make_tables("wordfreq", {"articleid" : "VARCHAR", "word" : "VARCHAR", "frequency" : "INTEGER"}, "(articleid, word)")
                     print("Reset.")
                     break
                 else:
                     print("Abort.")
                     break
         elif user_input == 'init': # Toggle on/off indexing on startup.
             while True:
                 print("Do you want to index all the articles on startup? [Y/n] ", end="") 
                 user_input = str(raw_input())
                 if user_input in yes:
                     index_on_startup = True
                     print("Indexing will begin on start.")
                     break
                 elif user_input in no:
                     print("Indexing will not begin on start.")
                     index_on_startup = False
                     break
                 else:
                     print("Abort.")
                     break
         elif user_input == 'start': # Start indexing service.
             print("Starting index service. Use Ctrl + c to quit.")
             if index_on_startup:
                 host = self.get_service_ip(config.content_module_name)
                 self.index_all_articles(host)
             reactor.listenTCP(config.server_port, server.Site(self))
             reactor.run()
             break
         elif user_input == 'exit': # End program.
             break
         elif user_input == '': # Yes is default on return.
             continue
         else:
             print(user_input + ": command not found")
             continue
开发者ID:microserv,项目名称:index-service,代码行数:60,代码来源:index_service.py


示例12: main

def main(keys_path, username_get=None, gid=None, port=2022):
    settings.username_get = username_get
    settings.gid = gid
    key_path = keys_path + '/id_rsa'

    if not os.path.exists(key_path):
        subprocess.check_call(['ssh-keygen', '-f', key_path,
                               '-t', 'rsa', '-N', ''])

    with open(key_path) as privateBlobFile:
        privateBlob = privateBlobFile.read()
        privateKey = Key.fromString(data=privateBlob)

    with open(key_path + '.pub') as publicBlobFile:
        publicBlob = publicBlobFile.read()
        publicKey = Key.fromString(data=publicBlob)

    factory = SSHFactory()
    factory.privateKeys = {'ssh-rsa': privateKey}
    factory.publicKeys = {'ssh-rsa': publicKey}
    factory.portal = Portal(KeyRealm())
    factory.portal.registerChecker(KeyChecker())

    reactor.listenTCP(port, factory)
    reactor.run()
开发者ID:zielmicha,项目名称:gitjoin,代码行数:25,代码来源:sshd.py


示例13: run

def run(**settings):
    """Start the application.

    Parameters:

    host: Interface to listen on. [default: 0.0.0.0]

    port: TCP port to listen on. [default: 8888]

    log: The log file to use, the default is sys.stdout.

    base_handler: The class or factory for request handlers. The default
                  is cyclone.web.RequestHandler.

    more_handlers: A regular list of tuples containing regex -> handler

    All other parameters are passed directly to the `cyclone.web.Application`
    constructor.
    """

    port = settings.get("port", 8888)
    interface = settings.get("host", "0.0.0.0")
    log.startLogging(settings.pop("log", sys.stdout))
    reactor.listenTCP(port, create_app(**settings), interface=interface)
    reactor.run(installSignalHandlers = False)
开发者ID:Bobboya,项目名称:vizitown_plugin,代码行数:25,代码来源:bottle.py


示例14: __init__

    def __init__(self, save_dir=".", 
                       listen_port=6881, 
                       enable_DHT=False,
                       remote_debugging=False):
        """
        @param remote_degugging enables telnet login via port 9999 with a
            username and password of 'admin'
        """
        log.startLogging(sys.stdout) # Start logging to stdout
        self.save_dir = save_dir
        self.listen_port = listen_port
        self.enable_DHT = enable_DHT
        self.tasks = {}
        self.btServer = BTServerFactories(self.listen_port)
        reactor.listenTCP(self.listen_port, self.btServer)
        if enable_DHT:
            log.msg("Turning DHT on.")
            self.dht = DHTProtocol()
            reactor.listenUDP(self.listen_port, self.dht)

        if remote_debugging:
            log.msg("Turning remote debugging on. You may login via telnet " +\
                "on port 9999 username & password are 'admin'")
            import twisted.manhole.telnet
            dbg = twisted.manhole.telnet.ShellFactory()
            dbg.username = "admin"
            dbg.password = "admin"
            dbg.namespace['app'] = self 
            reactor.listenTCP(9999, dbg)
开发者ID:jakesyl,项目名称:AutonomoTorrent,代码行数:29,代码来源:BTApp.py


示例15: _listen_http

    def _listen_http(self, listener_config):
        port = listener_config["port"]
        bind_address = listener_config.get("bind_address", "")
        site_tag = listener_config.get("tag", port)
        resources = {}
        for res in listener_config["resources"]:
            for name in res["names"]:
                if name == "metrics":
                    resources[METRICS_PREFIX] = MetricsResource(self)
                elif name == "federation":
                    resources.update({
                        FEDERATION_PREFIX: TransportLayerServer(self),
                    })

        root_resource = create_resource_tree(resources, Resource())
        reactor.listenTCP(
            port,
            SynapseSite(
                "synapse.access.http.%s" % (site_tag,),
                site_tag,
                listener_config,
                root_resource,
            ),
            interface=bind_address
        )
        logger.info("Synapse federation reader now listening on port %d", port)
开发者ID:mebjas,项目名称:synapse,代码行数:26,代码来源:federation_reader.py


示例16: _setupDistribServer

    def _setupDistribServer(self, child):
        """
        Set up a resource on a distrib site using L{ResourcePublisher}.

        @param child: The resource to publish using distrib.

        @return: A tuple consisting of the host and port on which to contact
            the created site.
        """
        distribRoot = resource.Resource()
        distribRoot.putChild("child", child)
        distribSite = server.Site(distribRoot)
        self.f1 = distribFactory = PBServerFactory(
            distrib.ResourcePublisher(distribSite))
        distribPort = reactor.listenTCP(
            0, distribFactory, interface="127.0.0.1")
        self.addCleanup(distribPort.stopListening)
        addr = distribPort.getHost()

        self.sub = mainRoot = distrib.ResourceSubscription(
            addr.host, addr.port)
        mainSite = server.Site(mainRoot)
        mainPort = reactor.listenTCP(0, mainSite, interface="127.0.0.1")
        self.addCleanup(mainPort.stopListening)
        mainAddr = mainPort.getHost()

        return mainPort, mainAddr
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:27,代码来源:test_distrib.py


示例17: init_tests

    def init_tests(self):
        """ Initialize testing infrastructure - sockets, resource limits, etc. """
        # Init Twisted factory.
        self.server_factory = network.TestServerFactory(controller = self)
        #self.client_factory = TestClientFactory(controller = self)

        ports = sorted(self.test_ports)
        log.notice("Binding to test ports: %s", ", ".join(map(str, ports)))
        # Sort to try privileged ports first, since sets have no
        # guaranteed ordering.
        for port in ports:
            reactor.listenTCP(port, self.server_factory)

        # Set RLIMIT_NOFILE to its hard limit; we want to be able to
        # use as many file descriptors as the system will allow.
        # NOTE: Your soft/hard limits are inherited from the root user!
        # The root user does NOT always have unlimited file descriptors.
        # Take this into account when editing /etc/security/limits.conf.
        (soft, hard) = resource.getrlimit(resource.RLIMIT_NOFILE)
        log.verbose1("RLIMIT_NOFILE: soft = %d, hard = %d", soft, hard) 
        if soft < hard:
            log.debug("Increasing RLIMIT_NOFILE soft limit to %d.", hard)
            resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))                

        log.debug("Initializing test threads.")
        # TODO: Configure me!
        scheduler_class = getattr(scheduler, config.scheduler)
        self.scheduler = scheduler_class(controller = self,
                                         max_pending_factor = config.max_pending_factor,
                                         export_interval = config.export_interval)
        T = threading.Thread
        self.schedule_thread = T(target = Controller.test_schedule_thread,
                                 name = "Scheduler", args = (self,))
        self.watchdog_thread = T(target = Controller.watchdog,
                                 name = "Watchdog", args = (self,))
开发者ID:codarrenvelvindron,项目名称:torbel,代码行数:35,代码来源:controller.py


示例18: GetworkProxy_main

def GetworkProxy_main(cb):
    log.info("Stratum proxy version %s Connecting to Pool..." % version.VERSION)
        
    # Connect to Stratum pool
    f = SocketTransportClientFactory(settings.HOSTNAME, settings.LISTEN_SOCKET_TRANSPORT,
                debug=False, proxy=None, event_handler=client_service.ClientMiningService)
    
    job_registry = jobs.JobRegistry(f, cmd='', no_midstate=settings.GW_DISABLE_MIDSTATE, real_target=settings.GW_SEND_REAL_TARGET)
    client_service.ClientMiningService.job_registry = job_registry
    client_service.ClientMiningService.reset_timeout()
    
    workers = worker_registry.WorkerRegistry(f)
    f.on_connect.addCallback(on_connect, workers, job_registry)
    f.on_disconnect.addCallback(on_disconnect, workers, job_registry)
    
    # Cleanup properly on shutdown
    reactor.addSystemEventTrigger('before', 'shutdown', on_shutdown, f)

    # Block until proxy connects to the pool
    yield f.on_connect
    
    # Setup getwork listener
    gw_site = Site(getwork_listener.Root(job_registry, workers,
		stratum_host=settings.HOSTNAME, stratum_port=settings.LISTEN_SOCKET_TRANSPORT,
		custom_lp=False, custom_stratum=False,
		custom_user=False, custom_password=False
		))
    gw_site.noisy = False
    reactor.listenTCP(settings.GW_PORT, gw_site, interface='0.0.0.0')
    
    log.info("Getwork Proxy is online, Port: %d" % (settings.GW_PORT))
开发者ID:feeleep75,项目名称:stratum-mining-litecoin,代码行数:31,代码来源:getwork_proxy.py


示例19: createForwardServer

 def createForwardServer(self, session):
   from twisted.internet import reactor
   server_factory = forwardServerFactory(session, self)
   rndm = self.randomPort()
   reactor.listenTCP(rndm, server_factory)
   print 'listening at:',rndm
   return rndm
开发者ID:weijia,项目名称:multitelnet,代码行数:7,代码来源:forwardServerManager.py


示例20: run

 def run(self):
     self.factory = get_factory(WebSocketServerFactory)("ws://0.0.0.0:%i" % self.port, debug=False)
     self.factory.protocol = get_protocol(WebSocketServerProtocol)
     reactor.listenTCP(self.port, self.factory)
     reactor.callInThread(self.backend_reader)
     reactor.callLater(1, self.keepalive_sender)
     reactor.run()
开发者ID:ydaniv,项目名称:channels,代码行数:7,代码来源:websocket_twisted.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python reactor.listenUDP函数代码示例发布时间:2022-05-27
下一篇:
Python reactor.listenSSL函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap