[英]Python3 asyncio - running two servers in own thread
I have my servers classes inherited from BaseServer
: 我有从
BaseServer
继承的服务器类:
class BaseServer(object):
def __init__(self, host, port):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.instance = asyncio.start_server(self.handle_connection, host = host, port = port)
async def handle_connection(self, reader: StreamReader, writer: StreamWriter):
pass
def start(self):
# wrapping coroutine into ensure_future to allow it to call from call_soon
# wrapping into lambda to make it callable
callback = asyncio.ensure_future(self.instance)
self.loop.call_soon(lambda: callback)
self.loop.run_forever()
self.loop.close()
def stop(self):
self.loop.call_soon_threadsafe(self.loop.stop)
@staticmethod
def get_instance():
return BaseServer(None, None)
I need two servers running in own thread to processing requests in parallel. 我需要在自己的线程中运行的两个服务器来并行处理请求。 But when I trying to run them as needed, only first server is running.
但是,当我尝试根据需要运行它们时,只有第一台服务器正在运行。 Below how I run them:
下面是我的运行方式:
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def run():
pool = ThreadPoolExecutor(max_workers=cpu_count())
await loop.run_in_executor(pool, Server1.get_instance().start)
await loop.run_in_executor(pool, Server2.get_instance().start)
loop.run_until_complete(run())
asyncio.set_event_loop
is calling from def __init__
I got next error: asyncio.set_event_loop
从调用def __init__
我得到了一个错误: RuntimeError: There is no current event loop in thread 'Thread-1'.
RuntimeError:线程“ Thread-1”中没有当前事件循环。
But if I remove asyncio.set_event_loop
from def __init__
and move it to def start
error disappears. 但是,如果我从
def __init__
删除asyncio.set_event_loop
并将其移至def start
错误将消失。 Why this happened? 为什么会这样?
Following up on OP's comment: 跟进OP的评论:
But running two servers via run_until_complete in the same loop blocks loop for one of servers to process request to another, isn't it ?
但是在同一个循环中通过run_until_complete运行两个服务器,其中一个服务器处理对另一个服务器的请求,不是吗? How to run two servers correctly ?
如何正确运行两台服务器?
Here is a modified version of the TCP server example from the asyncio documentation for python 3.5: 这是python 3.5的asyncio文档中TCP服务器示例的修改版本:
# Start server 1
coro1 = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
server1 = loop.run_until_complete(coro1)
print('Serving 1 on {}'.format(server1.sockets[0].getsockname()))
# Start server 2
coro2 = asyncio.start_server(handle_echo, '127.0.0.1', 8889, loop=loop)
server2 = loop.run_until_complete(coro2)
print('Serving 2 on {}'.format(server2.sockets[0].getsockname()))
# Serve requests until Ctrl+C is pressed
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the servers
server1.close()
loop.run_until_complete(server1.wait_closed())
server2.close()
loop.run_until_complete(server2.wait_closed())
# Close the loop
loop.close()
Note that with python 3.7 additions to asyncio, it would look much nicer : 请注意,使用python 3.7对asyncio的添加,它看起来会更好 :
async def main():
server1 = await asyncio.start_server(
handle_echo, '127.0.0.1', 8888)
addr1 = server1.sockets[0].getsockname()
print(f'Serving 1 on {addr1}')
server2 = await asyncio.start_server(
handle_echo, '127.0.0.1', 8889)
addr2 = server2.sockets[0].getsockname()
print(f'Serving 2 on {addr2}')
async with server1, server2:
await asyncio.gather(
server1.serve_forever(), server2.serve_forever())
asyncio.run(main())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.