Python Asyncio - 服务器能够在不同时间接收多条命令并进行处理
Python Asyncio - Server able to receive multi-commands in different times and processing it
我正在使用 Python 中的 AsyncIO 库构建 client/server 通信。现在我正试图让我的服务器能够接收多个命令,处理它并在完成后回复。
我是说:
服务器已收到命令,并且可以在处理之前收到的命令的同时接收 "n" 个更多命令。
有人可以帮助我如何找到一些示例,或者如何是进行搜索的最佳方式吗?
I mean: Server received the command and can be able to receive "n" more commands while processing the previous received commands.
如果我没理解错的话,您希望服务器在后台处理客户端的命令,即在命令 运行ning 期间继续与客户端通话.这允许客户端在不等待第一个命令的情况下将多个命令排队; http 调用此技术 pipelining.
由于 asyncio 允许在 "background" 中创建 运行 的轻量级任务,因此实现此类服务器实际上非常容易。这是一个示例服务器,它在休眠一段时间后响应一条消息,并在任何时候接受多个命令:
import asyncio
async def serve(r, w):
loop = asyncio.get_event_loop()
while True:
cmd = await r.readline()
if not cmd:
break
if not cmd.startswith(b'sleep '):
w.write(b'bad command %s\n' % cmd.strip())
continue
sleep_arg = int(cmd[6:]) # how many seconds to sleep
loop.create_task(cmd_sleep(w, sleep_arg))
async def cmd_sleep(w, interval):
w.write(f'starting sleep {interval}\n'.encode())
await asyncio.sleep(interval)
w.write(f'ended sleep {interval}\n'.encode())
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.start_server(serve, None, 4321))
loop.run_forever()
main()
我正在使用 Python 中的 AsyncIO 库构建 client/server 通信。现在我正试图让我的服务器能够接收多个命令,处理它并在完成后回复。 我是说: 服务器已收到命令,并且可以在处理之前收到的命令的同时接收 "n" 个更多命令。
有人可以帮助我如何找到一些示例,或者如何是进行搜索的最佳方式吗?
I mean: Server received the command and can be able to receive "n" more commands while processing the previous received commands.
如果我没理解错的话,您希望服务器在后台处理客户端的命令,即在命令 运行ning 期间继续与客户端通话.这允许客户端在不等待第一个命令的情况下将多个命令排队; http 调用此技术 pipelining.
由于 asyncio 允许在 "background" 中创建 运行 的轻量级任务,因此实现此类服务器实际上非常容易。这是一个示例服务器,它在休眠一段时间后响应一条消息,并在任何时候接受多个命令:
import asyncio
async def serve(r, w):
loop = asyncio.get_event_loop()
while True:
cmd = await r.readline()
if not cmd:
break
if not cmd.startswith(b'sleep '):
w.write(b'bad command %s\n' % cmd.strip())
continue
sleep_arg = int(cmd[6:]) # how many seconds to sleep
loop.create_task(cmd_sleep(w, sleep_arg))
async def cmd_sleep(w, interval):
w.write(f'starting sleep {interval}\n'.encode())
await asyncio.sleep(interval)
w.write(f'ended sleep {interval}\n'.encode())
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.start_server(serve, None, 4321))
loop.run_forever()
main()