我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用asyncio.start_server()。
def listen(self): self.loop.run_until_complete(start_server(self.handle_connection, self.host, self.port, loop=self.loop))
def main(address='127.0.0.1', port=2323): # <1> port = int(port) loop = asyncio.get_event_loop() server_coro = asyncio.start_server(handle_queries, address, port, loop=loop) # <2> server = loop.run_until_complete(server_coro) # <3> host = server.sockets[0].getsockname() # <4> print('Serving on {}. Hit CTRL-C to stop.'.format(host)) # <5> try: loop.run_forever() # <6> except KeyboardInterrupt: # CTRL+C pressed pass print('Server shutting down.') server.close() # <7> loop.run_until_complete(server.wait_closed()) # <8> loop.close() # <9>
def main(address='127.0.0.1', port=8888): port = int(port) loop = asyncio.get_event_loop() coro = asyncio.start_server(handle_queries, address, port, loop=loop) server = loop.run_until_complete(coro) host = server.sockets[0].getsockname() print('Serving on {}. Hit CTRL-C to stop.'.format(host)) try: loop.run_forever() except KeyboardInterrupt: # CTRL+C pressed pass server.close() loop.run_until_complete(server.wait_closed()) loop.close()
def start_server(host='127.0.0.1', port=17000, db_name='db'): global db db = shelfdb.open(db_name) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) loop = asyncio.get_event_loop() server = asyncio.start_server(handler, host, port, loop=loop) server = loop.run_until_complete(server) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) print('Database :', db_name) print('pid :', os.getpid()) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server server.close() db.close() loop.run_until_complete(server.wait_closed()) loop.close()
def test_send_message(): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) plaintext_protocol = PlaintextProtocol() loop = asyncio.get_event_loop() async with AIOGraphite( '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, plaintext_protocol, loop=loop) as aiographite: message = "hello world !" await aiographite._send_message(message.encode("ascii")) reader = aiographite._reader writer = aiographite._writer writer.write_eof() await writer.drain() data = (await reader.read()).decode("utf-8") writer.close() server.close() assert message == data
def test_send(): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) plaintext_protocol = PlaintextProtocol() loop = asyncio.get_event_loop() async with AIOGraphite('127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, plaintext_protocol, loop=loop) as aiographite: metric = 'sproc%20performance.velo%40zillow%2Ecom.%3A%3AEH12' value = 3232 timestamp = 1471640923 message = ('sproc%20performance.velo%40zillow%2E' 'com.%3A%3AEH12 3232 1471640923\n') await aiographite.send(metric, value, timestamp) reader = aiographite._reader writer = aiographite._writer writer.write_eof() await writer.drain() data = (await reader.read()).decode("utf-8") writer.close() assert message == data server.close()
def test_full_path(): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) plaintext_protocol = PlaintextProtocol() loop = asyncio.get_event_loop() aiographite = await connect( '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, plaintext_protocol, loop=loop) metric = 'sproc%20performance.velo%40zillow%2Ecom.%3A%3AEH12' value = 3232 timestamp = 1471640923 message = ('sproc%20performance.velo%40zillow%2E' 'com.%3A%3AEH12 3232 1471640923\n') await aiographite.send(metric, value, timestamp) reader = aiographite._reader writer = aiographite._writer writer.write_eof() await writer.drain() data = (await reader.read()).decode("utf-8") writer.close() await aiographite.close() assert message == data server.close()
def start_server(self): """ Starts the listening server. :return: Server object if successful, otherwise None. :rtype: asyncio.Server """ nlog.info("Creating server listing on '{}:{}'...".format(self.host, self.port)) try: self.server = await asyncio.start_server(self.create_connection, self.host, self.port) nlog.info(self.log_prefix + "Success created server listing on '{}:{}'...".format(self.host, self.port)) except: self.startup_exception_info = sys.exc_info() nlog.exception(self.log_prefix + "Error opening server listening on '{}:{}'...".format(self.host, self.port)) self.started_semaphore.release() return self.server
def open_connection(self): try: server = await asyncio.start_server( self.handle_connection, host=self.host, port=self.port, loop=self.loop, ) try: await server.wait_closed() finally: server.close() await server.wait_closed() except asyncio.CancelledError: raise except Exception: logger.exception( "Unable to start TCP server on %s:%s.", self.host, self.port, )
def start(self) -> None: ''' Start socket server which will stream movie ''' self._logger.info('Server starting at = %s:%d', self.host, self.port) self._server = await asyncio.start_server(self._handle_client, self.host, self.port)
def __init__(self, host, port, ping=True, ping_interval=5, buffer_size=8192, max_frame_size=8192, max_connections=10, compression=True): self.clients = [] self.host = host self.port = port self.ping = ping self.ping_interval = ping_interval self.buffer_size = buffer_size self.max_frame_size = max_frame_size self.compression = compression self.server = asyncio.start_server(client_connected_cb=self.__client_connected, host=host, port=port, loop=loop) loop.run_until_complete(self.server) loop.run_forever()
def run(self, host: str="localhost", port: int=8000, debug: bool=False): """ start the http server :param host: The listening host :param port: The listening port :param debug: whether it is in debug mod or not """ if debug: print("Nougat is listening on http://{}:{}\n".format(host, port)) self.debug = debug loop = asyncio.new_event_loop() loop.run_until_complete(self.start_server(host, port)) try: loop.run_forever() except KeyboardInterrupt: loop.close()
def start(self): """Start accepting connections. Only use this method if you are not using the server as an asynchronous context manager. See: - :py:meth:`aiotk.TCPServer.wait_started` - :py:meth:`aiotk.TCPServer.close` """ if self._server: raise Exception('Already running.') self._server = self._loop.create_task(asyncio.start_server( self._client_connected, host=self._host, port=self._port, )) # NOTE: start is synchronous, so we can't await in there.
def start(self): loop = asyncio.get_event_loop() ssl_context = None if CONF.cert: ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ssl_context.load_cert_chain(certfile=CONF.cert, keyfile=CONF.key) coro = asyncio.start_server(self.handle_telnet, CONF.host, CONF.port, ssl=ssl_context, loop=loop) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed LOG.info("Serving on %s", server.sockets[0].getsockname()) LOG.info("Log directory: %s", CONF.serial_log_dir) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close()
def startup(self, port=None, socket_path=None): if port: await asyncio.start_server( self._client_connected, port=port, loop=self.loop, ) logger.info('server started on port %s' % (port,)) elif socket_path: await asyncio.start_unix_server( self._client_connected, path=socket_path, loop=self.loop, ) logger.info('server started on unix path %s' % (socket_path,)) else: raise ValueError('one of port and socket_path must be provided.') for startup in self.startups: await startup(self.loop, self)
def run_server(bind='127.0.0.1', port=8888): # Start the server loop = asyncio.get_event_loop() coro = asyncio.start_server(euclidean_norm_handler, bind, port) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close() # Main execution
def main(): urls = ["http://google.com", "http://app.ustudio.com"] tasks = asyncio.wait([fetch(url) for url in urls]) loop = asyncio.get_event_loop() loop.run_until_complete(tasks) print("-----------") init = asyncio.start_server(handle_client, "127.0.0.1", 8001, loop=loop) server = loop.run_until_complete(init) client = asyncio.open_connection("127.0.0.1", 8001) response = handle_message(client) loop.run_until_complete(response) server.close() loop.run_until_complete(server.wait_closed()) loop.close() print("Finished.")
def launch(self): """ run the videoscreen """ print("launching on {}:{}...".format(self.address, self.port)) loop = asyncio.get_event_loop() coro = asyncio.start_server(self.new_client, self.address, self.port) server = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass server.close() loop.run_until_complete(server.wait_closed()) loop.close()
def test_issue_server(event_loop, unused_tcp_port): cs = CredentialServer() coro = asyncio.start_server(cs.handle_cmd, '127.0.0.1', unused_tcp_port, loop=event_loop) event_loop.create_task(coro) (G, g, h, o) = cs.params # User creates a public / private key pair keypair = cred_UserKeyge(cs.params) # User packages credentials LT_user_ID = o.random() timeout = 100 key = 200 value = 300 public_attr = [ key, value, timeout ] private_attr = [ LT_user_ID ] resp = event_loop.run_until_complete(issue_client('127.0.0.1', unused_tcp_port, cs.params, cs.ipub, keypair, public_attr, private_attr, event_loop))
def launch(host, port): server = await asyncio.start_server(serve, host, port) await server.wait_closed()
def echo_server(): yield from asyncio.start_server(handle_connection, 'localhost', 8000) print("[server] return...") # # ????: # - ??????? #
def worker_main(loop, pidx, args): # Create a listening socket with SO_REUSEPORT option so that each worker # process can share the same listening port and the kernel balances # incoming connections across multiple worker processes. server = await asyncio.start_server(echo, '0.0.0.0', 8888, reuse_port=True, loop=loop) print(f'[{pidx}] started') yield # wait until terminated server.close() await server.wait_closed() print(f'[{pidx}] terminated')
def main(): arg = argparse.ArgumentParser(description='ShelfDB Asyncio Server') arg.add_argument('--host', nargs='?', type=str, default='0.0.0.0', help='server host') arg.add_argument('--port', nargs='?', type=int, default=17000, help='server port') arg.add_argument('--db', nargs='?', default='db', help='server database') arg = arg.parse_args() start_server(arg.host, arg.port, arg.db)
def test_send_None(): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) plaintext_protocol = PlaintextProtocol() loop = asyncio.get_event_loop() async with AIOGraphite('127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, plaintext_protocol, loop=loop) as aiographite: metric = None value = 3232 timestamp = 1471640923 # Should not raise exception await aiographite.send(metric, value, timestamp) server.close()
def test_send_multiple(): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) pickle = PickleProtocol() loop = asyncio.get_event_loop() async with AIOGraphite('127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, pickle, loop=loop) as aiographite: dataset = [('sproc%20performance.velo%40zillow%2Ecom.%3A%3AEH12', 3233, 1471640923), ('dit_400.zpid%40zillow%2Ecom.EHT%3A%3Adisk_usage_per_host', 2343, 1471640976)] await aiographite.send_multiple(dataset) reader = aiographite._reader writer = aiographite._writer writer.write_eof() await writer.drain() data = (await reader.read()) writer.close() message = ( b"\x00\x00\x00\x9c\x80\x02]q\x00(X2\x00\x00\x00sproc" b"%20performance.velo%40zillow%2Ecom.%3A%3AEH12q\x01J[u\xb7WM" b"\xa1\x0c\x86q\x02\x86q\x03X8\x00\x00\x00dit_400.zpid%40zillow" b"%2Ecom.EHT%3A%3Adisk_usage_per_hostq\x04J\x90u\xb7WM'\t\x86q" b"\x05\x86q\x06e.") assert message == data server.close()
def test_send_multiple_None(dataset): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) pickle = PickleProtocol() loop = asyncio.get_event_loop() async with AIOGraphite('127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, pickle, loop=loop) as aiographite: await aiographite.send_multiple(dataset) server.close()
def test_wrong_protocol(): server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) test_protocol = TestProtocol() loop = asyncio.get_event_loop() with pytest.raises(Exception): AIOGraphite('127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, test_protocol, loop=loop) server.close()
def test_autoreconnect(): # Initialize server server = await asyncio.start_server(server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT) plaintext_protocol = PlaintextProtocol() loop = asyncio.get_event_loop() aiographite = AIOGraphite( '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, plaintext_protocol, loop=loop) message = "hello!" await aiographite._connect() # disconnect await aiographite._disconnect() # automatically connect if desconnected await aiographite._send_message(message.encode("ascii")) reader = aiographite._reader writer = aiographite._writer writer.write_eof() await writer.drain() data = (await reader.read()).decode("utf-8") writer.close() assert message == data # Close Connection by closing server server.close() with pytest.raises(Exception): await aiographite._send_message(message.encode("ascii")) reader = aiographite._reader writer = aiographite._writer assert reader is None and writer is None
def test_send_message_timeout(mock_streamWriter_drain): loop = asyncio.get_event_loop() server = loop.run_until_complete(asyncio.start_server( server_handler, '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT)) plaintext_protocol = PlaintextProtocol() aiographite = AIOGraphite( '127.0.0.1', DEFAULT_GRAPHITE_PLAINTEXT_PORT, plaintext_protocol, loop=loop, timeout=0.01) message = "hello!" starttime = time.time() loop.run_until_complete(aiographite._send_message(message.encode("ascii"))) endtime = time.time() elapsed_time = endtime - starttime assert elapsed_time < 1 server.close()
def handle(self, *args, bind='localhost', port=8765, http_port=8001, **kwargs): LOGGER.addHandler(logging.StreamHandler()) LOGGER.setLevel(logging.DEBUG) server = ArrayServer() loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.start_server(server.handle_client, bind, port)) loop.run_until_complete( asyncio.start_server(server.handle_http, bind, http_port)) loop.run_forever()
def __init__(self, host, port, connections, loop=None): self.host = host #: Listening host self.port = port #: Listening port self.loop = loop or event_loop.get() #: Event loop onto which the listener is running. self.server = None #: class:`asyncio.Server` instance used by the listener. self.connections = connections #: Dictionary containing all connections. asyncio.run_coroutine_threadsafe(self.start_server(), self.loop) self.started_semaphore = asyncio.Semaphore(0) self.startup_exception_info = None
def _createServer(host, port): """ Create async server that listens host:port, reads client request and puts value to some future that can be used then for checks :return: reference to server and future for request """ indicator = asyncio.Future() async def _handle(reader, writer): raw = await reader.readline() request = raw.decode("utf-8") indicator.set_result(request) server = await asyncio.start_server(_handle, host, port) return server, indicator
def start_server(self, host: str, port: int): return await asyncio.start_server(self.http_serve, host, port)
def start(self, loop: asyncio.AbstractEventLoop): self.server = await asyncio.start_server(self.accept_client, ADDRESS, PORT, loop=loop) logger.info("Started the commloop server.")
def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.server = Server() self.server.add_route('/hello', Handler()) self.port = get_free_port() self.url = 'http://127.0.0.1:%d' % (self.port, ) self.async_server = self.loop.run_until_complete( asyncio.start_server( self.server._handle, '127.0.0.1', self.port, loop=self.loop ) )
def serve(self, port=8000, host='0.0.0.0'): loop = asyncio.get_event_loop() loop.run_until_complete(self.initialize()) print('Serving on %s:%d' % (host, port)) loop.create_task(asyncio.start_server(self._handle, host, port)) loop.run_forever() loop.close()
def run(self): self.start_server() self.loop.run_forever() self.loop.close() smconn.SMThread.run(self)
def start_server(self): """ Start the server in the given loop """ self._serv = self.loop.run_until_complete(asyncio.start_server( self._accept_client, host=self.ip, port=self.port, loop=self.loop, )) return self._serv
def start(self): for port in PeerTCPServer.PORT_RANGE: try: self._server = await asyncio.start_server(self._accept, port=port) except asyncio.CancelledError: raise except Exception as e: logger.debug('exception on starting server on port %s: %r', port, e) else: self._port = port logger.info('server started on port %s', port) return else: logger.warning('failed to start a server')
def start(self): for port in ControlServer.PORT_RANGE: try: self._server = await asyncio.start_server(self._accept, host=ControlServer.HOST, port=port) except asyncio.CancelledError: raise except Exception as e: logger.debug('exception on starting server on port %s: %r', port, e) else: logger.info('server started on port %s', port) return else: raise RuntimeError('Failed to start a control server')
def create_server(service, handler, address=('127.0.0.1', 6000), loop=None, protocol_cls=TBinaryProtocol, timeout=None, **kw ): """ create a thrift server. This function is a :ref:`coroutine <coroutine>`. :param service: thrift Service :param handler: a dispatcher object which is a namespace for all thrift api functions. :param address: (host, port) tuple, default is ('127.0.0.1', 6000) :param loop: :class:`Eventloop <asyncio.AbstractEventLoop>` instance :param protocol_cls: thrift protocol class, default is :class:`TBinaryProtocol` :param timeout: server side timeout, default is None :param kw: params relaied to asyncio.start_server :return: a :class:`Server` object which can be used to stop the service """ host, port = address processor = TProcessor(service, handler) if loop is None: loop = asyncio.get_event_loop() server = yield from asyncio.start_server( Server(processor, protocol_cls, timeout=timeout), host, port, loop=loop, **kw) return server
def start_server(self): """ Starts listening asynchronously for TCP connections on a socket and passes each connection to the HTTPServer.handle_connection method. """ if not self._server: self.loop = asyncio.get_event_loop() self._server = HTTPServer(self.router, self.http_parser, self.loop) self._connection_handler = asyncio.start_server( self._server.handle_connection, host=self.host, port=self.port, reuse_address=True, reuse_port=True, loop=self.loop) logger.info('Starting server on {0}:{1}'.format( self.host, self.port)) self.loop.run_until_complete(self._connection_handler) try: self.loop.run_forever() except KeyboardInterrupt: logger.info('Got signal, killing server') except DiyFrameworkException as e: logger.error('Critical framework failure:') logger.error(e.__traceback__) finally: self.loop.close() else: logger.info('Server already started - {0}'.format(self))
def listen(self, *, loop: asyncio.AbstractEventLoop, config): coro = asyncio.start_server( self.handle_incoming_request, '0.0.0.0', self.port, loop=loop) self._server = loop.run_until_complete(coro) print('-- Listening for HTTP on port {} --'.format(self.port))
def start(self, loop): print("Listening on {} {}".format(self.address, self.port)) await asyncio.start_server( partial(self.handle_client, loop), self.address, self.port)
def set_up_server(): global loop, server loop = uvloop.new_event_loop() asyncio.set_event_loop(loop) register('echo', echo) register('echo_delayed', echo_delayed) register('raise_error', raise_error) coro = asyncio.start_server(serve, HOST, PORT) server = loop.run_until_complete(coro)