本文整理汇总了Python中twisted.internet.endpoints.serverFromString函数的典型用法代码示例。如果您正苦于以下问题:Python serverFromString函数的具体用法?Python serverFromString怎么用?Python serverFromString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了serverFromString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/.b07'))
api = b07.api.API(reactor,
config.get('ingress', 'email'),
config.get('ingress', 'password'))
http_root = Redirect('https://localhost:{}/'.format(config.get('server', 'https_port')))
http_factory = Site(http_root)
http_endpoint = endpoints.serverFromString(reactor,
'tcp:{}'.format(config.get('server', 'http_port')))
http_endpoint.listen(http_factory)
https_root = File(os.path.expanduser(config.get('server', 'web_root')))
https_root.indexNames = ['index.html']
https_factory = Site(https_root)
https_endpoint = endpoints.serverFromString(reactor,
'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'https_port'),
os.path.expanduser(config.get('server', 'ssl_key')),
os.path.expanduser(config.get('server', 'ssl_cert'))))
https_endpoint.listen(https_factory)
wsfactory = Factory()
wsfactory.protocol = WebSocketProtocol
wss_endpoint = endpoints.serverFromString(reactor,
'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'wss_port'),
os.path.expanduser(config.get('server', 'ssl_key')),
os.path.expanduser(config.get('server', 'ssl_cert'))))
wss_endpoint.listen(txws.WebSocketFactory(wsfactory))
reactor.run()
示例2: main
def main():
log.startLogging(sys.stdout)
startPort = 3000
lastServerEndpoint = 'tcp:interface=127.0.0.1:%s' % startPort
torAgent = TorAgent(reactor)
serverEndpoint = serverFromString(reactor, lastServerEndpoint)
connectDeferred = serverEndpoint.listen(AgentProxyFactory(torAgent))
endpoint = []
agent = []
for x in range(10):
endpoint = clientFromString(reactor, "tcp:127.0.0.1:%s" % (startPort + x))
proxyAgent = ProxyAgent(endpoint)
serverEndpoint = serverFromString(reactor, "tcp:interface=127.0.0.1:%s" % (startPort + x + 1))
connectDeferred = serverEndpoint.listen(AgentProxyFactory(proxyAgent))
# XXX
def clientConnectionFailed(factory, reason):
log.err(reason)
log.err("httpTorProxy: clientConnectionFailed")
connectDeferred.addErrback(clientConnectionFailed)
reactor.run()
示例3: __init__
def __init__(self, reactor, cap_table, http_endpoint, ws_endpoint, root_cap, title):
# Constants
self.__http_endpoint_string = str(http_endpoint)
self.__http_endpoint = endpoints.serverFromString(reactor, self.__http_endpoint_string)
self.__ws_endpoint = endpoints.serverFromString(reactor, str(ws_endpoint))
self.__visit_path = _make_cap_url(root_cap)
wcommon = WebServiceCommon(
reactor=reactor,
title=title,
ws_endpoint_string=ws_endpoint)
# TODO: Create poller actually for the given reactor w/o redundancy -- perhaps there should be a one-poller-per-reactor map
subscription_context = SubscriptionContext(reactor=reactor, poller=the_poller)
def resource_factory(entry_point):
# TODO: If not an IWebEntryPoint, return a generic result
return IWebEntryPoint(entry_point).get_entry_point_resource(wcommon=wcommon) # pylint: disable=redundant-keyword-arg
server_root = CapAccessResource(cap_table=cap_table, resource_factory=resource_factory)
_put_root_static(wcommon, server_root)
if UNIQUE_PUBLIC_CAP in cap_table:
# TODO: consider factoring out "generate URL for cap"
server_root.putChild('', Redirect(_make_cap_url(UNIQUE_PUBLIC_CAP)))
self.__ws_protocol = txws.WebSocketFactory(
FactoryWithArgs.forProtocol(OurStreamProtocol, cap_table, subscription_context))
self.__site = _SiteWithHeaders(server_root)
self.__ws_port_obj = None
self.__http_port_obj = None
示例4: coerce_to_server_endpoint
def coerce_to_server_endpoint(reactor, ep_descr):
"""Given a string, attempt to produce a server endpoint.
If the string describes an endpoint directly, we use that; otherwise,
assume it's an attempt to provide a TCP endpoint and try variations on
that in the hope that one is parseable.
Parameters
----------
reactor : `implements twisted.internet.interfaces.IReactorCore`
Twisted reactor to use in constructing endpoint.
ep_descr : `str`
String describing the desired endpoint.
"""
try:
# Maybe this already is a valid endpoint.
return serverFromString(reactor, ep_descr)
except (ValueError, TypeError):
pass
try:
# Assume it just needs "tcp:" prepended.
return serverFromString(reactor, f"tcp:{ep_descr}")
except (ValueError, TypeError):
# At this point, we'll give up, and go back to the original bad parse.
serverFromString(reactor, ep_descr)
示例5: postOptions
def postOptions(self):
strport = self['strport']
factoryIdentifier = self['factory-identifier']
if strport is None or factoryIdentifier is None:
self.opt_help()
store = self.parent.parent.getStore()
storeID = int(factoryIdentifier)
try:
factory = store.getItemByID(storeID)
except KeyError:
print "%d does not identify an item." % (storeID,)
raise SystemExit(1)
else:
if not IProtocolFactoryFactory.providedBy(factory):
print "%d does not identify a factory." % (storeID,)
raise SystemExit(1)
else:
description = self.decodeCommandLine(strport)
try:
serverFromString(reactor, description.encode('ascii'))
except ValueError:
print "%r is not a valid port description." % (strport,)
raise SystemExit(1)
port = StringEndpointPort(
store=store, description=description, factory=factory)
installOn(port, store)
print "Created."
raise SystemExit(0)
示例6: main
def main(self, reactor, options):
certificates_path = FilePath(options["certificates-directory"])
ca = Certificate.loadPEM(
certificates_path.child(b"cluster.crt").getContent())
# This is a hack; from_path should be more
# flexible. https://clusterhq.atlassian.net/browse/FLOC-1865
control_credential = ControlCredential.from_path(
certificates_path, b"service")
top_service = MultiService()
persistence = ConfigurationPersistenceService(
reactor, options["data-path"])
persistence.setServiceParent(top_service)
cluster_state = ClusterStateService(reactor)
cluster_state.setServiceParent(top_service)
api_service = create_api_service(
persistence, cluster_state, serverFromString(
reactor, options["port"]),
rest_api_context_factory(ca, control_credential))
api_service.setServiceParent(top_service)
amp_service = ControlAMPService(
reactor, cluster_state, persistence, serverFromString(
reactor, options["agent-port"]),
amp_server_context_factory(ca, control_credential))
amp_service.setServiceParent(top_service)
return main_for_service(reactor, top_service)
示例7: __init__
def __init__(self, relayport, transitport, advertise_version,
db_url=":memory:", blur_usage=None):
service.MultiService.__init__(self)
self._blur_usage = blur_usage
self.db = get_db(db_url)
welcome = {
"current_version": __version__,
# adding .motd will cause all clients to display the message,
# then keep running normally
#"motd": "Welcome to the public relay.\nPlease enjoy this service.",
#
# adding .error will cause all clients to fail, with this message
#"error": "This server has been disabled, see URL for details.",
}
if advertise_version:
welcome["current_version"] = advertise_version
self.root = Root()
site = PrivacyEnhancedSite(self.root)
if blur_usage:
site.logRequests = False
r = endpoints.serverFromString(reactor, relayport)
self.relayport_service = ServerEndpointService(r, site)
self.relayport_service.setServiceParent(self)
self.relay = Relay(self.db, welcome, blur_usage) # accessible from tests
self.root.putChild(b"wormhole-relay", self.relay)
if transitport:
self.transit = Transit(self.db, blur_usage)
self.transit.setServiceParent(self) # for the timer
t = endpoints.serverFromString(reactor, transitport)
self.transport_service = ServerEndpointService(t, self.transit)
self.transport_service.setServiceParent(self)
示例8: __init__
def __init__(self, reactor, cap_table, read_only_dbs, writable_db, http_endpoint, ws_endpoint, root_cap, title, flowgraph_for_debug):
# Constants
self.__http_endpoint_string = http_endpoint
self.__http_endpoint = endpoints.serverFromString(reactor, http_endpoint)
self.__ws_endpoint = endpoints.serverFromString(reactor, ws_endpoint)
self.__visit_path = _make_cap_url(root_cap)
wcommon = WebServiceCommon(ws_endpoint_string=ws_endpoint)
def BoundSessionResource(session):
return SessionResource(session, wcommon, reactor, title, read_only_dbs, writable_db, flowgraph_for_debug)
server_root = CapAccessResource(cap_table=cap_table, resource_ctor=BoundSessionResource)
_put_root_static(server_root)
if UNIQUE_PUBLIC_CAP in cap_table:
# TODO: consider factoring out "generate URL for cap"
server_root.putChild('', Redirect(_make_cap_url(UNIQUE_PUBLIC_CAP)))
self.__ws_protocol = txws.WebSocketFactory(
FactoryWithArgs.forProtocol(OurStreamProtocol, cap_table))
self.__site = _SiteWithHeaders(server_root)
self.__ws_port_obj = None
self.__http_port_obj = None
示例9: main
def main():
options = docopt.docopt(__doc__)
port = int(options['<port>'])
rate = float(options['<rate>'])
label = options['<label>']
endpoints.serverFromString(reactor, "tcp:%d" % port).listen(SampleFactory(rate, label))
reactor.run()
示例10: do_listen
def do_listen(self, addr):
if not hasattr(self, "isClient") or not self.isClient:
self.isClient = False
else:
self.error("this is a client, doesn't support listen")
return
self._readHistoryFile('.peagunServer')
serverFromString(reactor, addr).listen(self.connectionManager)
示例11: start
def start():
game = MultisnakeServer()
server_update = task.LoopingCall(game.update)
server_update.start(1.0)
endpoints.serverFromString(reactor, "tcp:1234").listen(PlayerConnectionFactory(game))
reactor.run()
示例12: __init__
def __init__(self, rendezvous_web_port, transit_port,
advertise_version, db_url=":memory:", blur_usage=None,
signal_error=None):
service.MultiService.__init__(self)
self._blur_usage = blur_usage
db = get_db(db_url)
welcome = {
# The primary (python CLI) implementation will emit a message if
# its version does not match this key. If/when we have
# distributions which include older version, but we still expect
# them to be compatible, stop sending this key.
"current_cli_version": __version__,
# adding .motd will cause all clients to display the message,
# then keep running normally
#"motd": "Welcome to the public relay.\nPlease enjoy this service.",
# adding .error will cause all clients to fail, with this message
#"error": "This server has been disabled, see URL for details.",
}
if advertise_version:
welcome["current_cli_version"] = advertise_version
if signal_error:
welcome["error"] = signal_error
rendezvous = Rendezvous(db, welcome, blur_usage)
rendezvous.setServiceParent(self) # for the pruning timer
root = Root()
wsrf = WebSocketRendezvousFactory(None, rendezvous)
root.putChild(b"v1", WebSocketResource(wsrf))
site = PrivacyEnhancedSite(root)
if blur_usage:
site.logRequests = False
r = endpoints.serverFromString(reactor, rendezvous_web_port)
rendezvous_web_service = ServerEndpointService(r, site)
rendezvous_web_service.setServiceParent(self)
if transit_port:
transit = Transit(db, blur_usage)
transit.setServiceParent(self) # for the timer
t = endpoints.serverFromString(reactor, transit_port)
transit_service = ServerEndpointService(t, transit)
transit_service.setServiceParent(self)
# make some things accessible for tests
self._db = db
self._rendezvous = rendezvous
self._root = root
self._rendezvous_web_service = rendezvous_web_service
self._rendezvous_websocket = wsrf
if transit_port:
self._transit = transit
self._transit_service = transit_service
示例13: born
def born(self, data):
"""Method initiate TCL and UDP listeners."""
lc = LoopingCall(get_metrics, None)
lc.start(2)
reactor.listenUDP(self.UDP_PORT, NotificationUDPProcessor())
reactor.listenMulticast(self.MULTICAST_PORT,
MunticastNotificationProcessor(self.MULTICAST_IP), # add multicast 'born' processing
listenMultiple=True)
endpoints.serverFromString(reactor, "tcp:21999").listen(EchoFactory())
示例14: serve_forever
def serve_forever(port=9999):
"""Process incoming requests from the given socket.
:param port: The port to listen on
:type port: int
"""
endpoints.serverFromString(reactor, "tcp:{}".format(port)).listen(
MemcachedProtocolFactory()
)
reactor.run()
示例15: start_server
def start_server():
factory = KnowledgeFactory()
endpoints.serverFromString(
reactor, "tcp:%s" % config.SERVER_PORT).listen(factory)
logging.info("server started on port %d", config.SERVER_PORT)
reactor.run()
reactor.callLater(100, reactor.stop)
logging.info("server execution ended")