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
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)