我希望我的脚本做两件事:
我尝试将它们作为异步方法运行,如下面的示例代码,但是在listen()启动后阻止了foo()。
async def foo(name):
while True:
print(name, datetime.datetime.now())
await asyncio.sleep(1)
return await True
async def listen(port):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', port))
serversocket.listen(1)
while True:
connection, address = serversocket.accept()
buf = connection.recv(512)
if len(buf) > 0:
print(buf)
break
return True
async def go_foo(name='foo'):
b = await foo(name)
async def go_server(port=8089):
print('server on port', port)
b = await listen(port)
asyncio.ensure_future(go_server())
asyncio.ensure_future(go_foo())
loop = asyncio.get_event_loop()
loop.run_forever()
如何正确实现这样的任务?