How to pass additional parameters to handle_client coroutine?

前端 未结 1 1040
终归单人心
终归单人心 2021-01-13 05:09

The recommended way to use asyncio for a socket server is:

import asyncio

async def handle_client(reader, writer):
    request = (await reader.read(100)).de         


        
相关标签:
1条回答
  • 2021-01-13 05:35

    You can use a temporary function or a lambda:

    async def main():
        session = aiohttp.ClientSession()
        await asyncio.start_server(lambda r, w: handle_client(r, w, session),
                                   '', 55555)
    

    This works because even though the lambda is not technically a coroutine, it behaves just like one - when invoked it returns a coroutine object.

    For larger programs you might prefer a class-based approach where a class encapsulates the state shared by multiple clients without having to pass it explicitly. For example:

    class ClientContext:
        def __init__(self):
            self.session = aiohttp.ClientSession()
            # ... add anything else you will need "globally"
    
        async def handle_client(self, reader, writer):
            # ... here you get reader and writer, but also have
            # session etc as self.session ...
    
    async def main():
        ctx = ClientContext()
        await asyncio.start_server(ctx.handle_client), '', 55555)
    
    0 讨论(0)
提交回复
热议问题