问题
I am building a client/server communication by using the AsyncIO library in Python. Now I'm trying to make my server able to receive more than one command, process it and reply when done. I mean: Server received the command and can be able to receive "n" more commands while processing the previous received commands.
Could someone help me how to find some examples or than how is the best way to make a search?
回答1:
I mean: Server received the command and can be able to receive "n" more commands while processing the previous received commands.
If I understand you correctly, you want the server to process the client's command in the background, i.e. continue talking to the client while the command is running. This allows the client to queue multiple commands without waiting for the first one; http calls this technique pipelining.
Since asyncio allows creating lightweight tasks that run in the "background", it is actually quite easy to implement such server. Here is an example server that responds with a message after sleeping for an interval, and accepting multiple commands at any point:
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()
来源:https://stackoverflow.com/questions/51591151/python-asyncio-server-able-to-receive-multi-commands-in-different-times-and-pr