本文整理汇总了Python中twisted.internet.reactor.listenTCP函数的典型用法代码示例。如果您正苦于以下问题:Python listenTCP函数的具体用法?Python listenTCP怎么用?Python listenTCP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了listenTCP函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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则开始监听。
示例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()
示例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()
示例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)
示例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.")
示例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()
示例8: do_listening
def do_listening():
print "Listening for sensors..."
reactor.listenTCP(SENSORPORT, SensorFactory())
try:
reactor.run(installSignalHandlers=0)
except ReactorAlreadyRunning, e:
pass
示例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)
示例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)
示例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
示例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()
示例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)
示例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)
示例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)