Python 3.4+Async programmingfunction
asyncio.start_server()
streams
Starts a TCP server: for each incoming connection it calls a callback with a (StreamReader, StreamWriter) pair.
Syntax
server = await asyncio.start_server(client_connected_cb, host=None, port=None, *, limit=2**16, **kwds)
The server accepts connections right after the await; serve_forever() merely keeps the program alive. If the callback is a coroutine, each client gets its own task; an exception there does not crash the server, it is only logged, so handler errors are easy to miss. port=0 asks the OS for a free port; read the real one from server.sockets[0].getsockname(). async with server closes it on exit.
Examples
import asyncio
async def handle(reader, writer):
data = await reader.read(100)
writer.write(data.upper())
await writer.drain()
writer.close()
async def main():
server = await asyncio.start_server(handle, '127.0.0.1', 0)
host, port = server.sockets[0].getsockname()[:2]
print(host, port > 0) # → 127.0.0.1 True
async with server:
reader, writer = await asyncio.open_connection(host, port)
writer.write(b'abc')
print(await reader.read(100)) # → b'ABC'
writer.close()
await writer.wait_closed()
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy