本文整理匯總了Python中asyncio.start_server方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.start_server方法的具體用法?Python asyncio.start_server怎麽用?Python asyncio.start_server使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類asyncio
的用法示例。
在下文中一共展示了asyncio.start_server方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def main():
if config.tfo:
loop.set_exception_handler(silent_tpo_timeout_err_handler)
try:
server = loop.run_until_complete(
asyncio.start_server(dispatch_proxy, 'localhost', config.port))
except OSError:
die('wstan client failed to bind on localhost:%d' % config.port)
print('wstan client -- SOCKS5/HTTP(S) server listening on localhost:%d' % config.port)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
server.close()
loop.close()
示例2: test_invalid_login
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def test_invalid_login(self):
"""Tests if postgres server responds correctly to a invalid login attempt."""
def postgresql_login():
try:
psycopg2.connect("postgres://scott:tiger@0.0.0.0:2504/")
except psycopg2.OperationalError as e:
return e
return None
options = {'enabled': 'True', 'port': 2504}
postgresql_cap = postgresql.PostgreSQL(options, self.loop)
server_coro = asyncio.start_server(
postgresql_cap.handle_session, '0.0.0.0', 2504, loop=self.loop)
self.server = self.loop.run_until_complete(server_coro)
postgresql_task = self.loop.run_in_executor(None, postgresql_login)
login_exception = self.loop.run_until_complete(postgresql_task)
self.assertIsInstance(login_exception, psycopg2.OperationalError)
self.assertEqual(
str(login_exception),
'FATAL: password authentication failed for user "scott"\n')
示例3: test_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def test_connection(self):
""" Tests if the capability is up, and sending
HTTP 401 (Unauthorized) headers.
"""
def http_request():
client = httpclient.HTTPConnection('127.0.0.1', 8888)
client.request('GET', '/')
response = client.getresponse()
self.assertEqual(response.status, 401)
options = {'enabled': 'True', 'port': 8888, 'users': {'test': 'test'}}
http_cap = http.Http(options, self.loop)
server_coro = asyncio.start_server(
http_cap.handle_session, '0.0.0.0', 8888, loop=self.loop)
self.server = self.loop.run_until_complete(server_coro)
http_task = self.loop.run_in_executor(None, http_request)
self.loop.run_until_complete(http_task)
示例4: start_command_server
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def start_command_server():
if not ENABLED:
return
stop_command_server()
print(f'starting command server (view host / port in config file)')
try:
# noinspection PyTypeChecker
add_task(COMMAND_SERVER_TASK_ID, start_server(handle_client, HOST, PORT))
except Exception as e:
print(f"\n------COMMAND SERVER------\nfailed to bind/create command server\n"
f"this does not affect the bot, but it does mean that the command console will not work/be usable\n"
f"if this error happens a lot, command server can be disabled in the config.json in the bot's configs folder\n"
f'\nERROR INFO: {e}\n'
f'EXTENDED INFO: \n{format_exc()}\n\n'
f'------COMMAND SERVER------\n')
示例5: start
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def start(self):
""" Start the server socket
:return: False if an error prevented us from launching a connection thread. True if a connection thread has been started.
:rtype: bool
"""
if self._is_listening:
return False
try:
self.logger.info("Starting up TCP server socket {}".format(self.__our_socket))
self.__loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.__loop)
self.__coroutine = asyncio.start_server(self.__handle_connection, self._interfaceip, self._port)
self.__server = self.__loop.run_until_complete(self.__coroutine)
self.__listening_thread = threading.Thread(target=self.__listening_thread_worker, name='TCP_Server_{}'.format(self.name))
self.__listening_thread.daemon = True
self.__listening_thread.start()
except:
return False
return True
示例6: _setup_electrum_server
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def _setup_electrum_server(self, server_info):
async def methods(r, w):
responses = {
'server.version': 'mock 1.2 1.2',
'blockchain.scripthash.listunspent': 'cafebabe',
'something.subscribe': 'babe',
'server.ping': True
}
while 1:
data = await r.read(1024)
if not data:
w.close()
break
else:
d = json.loads(data.strip().decode())
command = d['method']
response = {'result': responses[command], 'id': d['id']}
res = json.dumps(response) + '\n'
w.write(res.encode())
await w.drain()
host = server_info.hostname
coro = asyncio.start_server(methods, host=host, port=50001, loop=self.loop)
return coro
示例7: test_protocol_timeout_on_starttls
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def test_protocol_timeout_on_starttls(
event_loop, bind_address, hostname, client_tls_context
):
async def client_connected(reader, writer):
await asyncio.sleep(1.0)
server = await asyncio.start_server(
client_connected, host=bind_address, port=0, family=socket.AF_INET
)
server_port = server.sockets[0].getsockname()[1]
connect_future = event_loop.create_connection(
SMTPProtocol, host=hostname, port=server_port
)
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0)
with pytest.raises(SMTPTimeoutError):
# STARTTLS timeout must be > 0
await protocol.start_tls(client_tls_context, timeout=0.00001)
server.close()
await server.wait_closed()
示例8: test_error_on_readline_with_partial_line
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def test_error_on_readline_with_partial_line(event_loop, bind_address, hostname):
partial_response = b"499 incomplete response\\"
async def client_connected(reader, writer):
writer.write(partial_response)
writer.write_eof()
await writer.drain()
server = await asyncio.start_server(
client_connected, host=bind_address, port=0, family=socket.AF_INET
)
server_port = server.sockets[0].getsockname()[1]
connect_future = event_loop.create_connection(
SMTPProtocol, host=hostname, port=server_port
)
_, protocol = await asyncio.wait_for(connect_future, timeout=1.0)
with pytest.raises(SMTPServerDisconnected):
await protocol.read_response(timeout=1.0)
server.close()
await server.wait_closed()
示例9: main
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
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>
示例10: main
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
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()
示例11: run_server
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
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
示例12: start
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def start(self):
loop = asyncio.get_event_loop()
tcp = self.get_config('app.contact.tcp')
loop.create_task(asyncio.start_server(self.tcp_handler.accept, *tcp.split(':'), loop=loop))
loop.create_task(self.operation_loop())
示例13: _start_tcp_listener
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def _start_tcp_listener(self) -> None:
# TODO: Support IPv6 addresses as well.
self._tcp_listener = await asyncio.start_server(
self.receive_handshake, host="0.0.0.0", port=self.port
)
示例14: __start_server
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def __start_server(self):
""" Run the server until shutdown is called """
self.server = await asyncio.start_server(
self.__handle_new_connection,
"0.0.0.0",
self.env.slave_config.PORT,
loop=self.loop,
)
Logger.info(
"Listening on {} for intra-cluster RPC".format(
self.server.sockets[0].getsockname()
)
)
示例15: start_server
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_server [as 別名]
def start_server(self):
coro = asyncio.start_server(self.new_peer, "0.0.0.0", self.port, loop=self.loop)
self.server = self.loop.run_until_complete(coro)
Logger.info("Self id {}".format(self.self_id.hex()))
Logger.info(
"Listening on {} for p2p".format(self.server.sockets[0].getsockname())
)