Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple server that runs a process for each client connection
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
import asyncio
import click
async def copy(src, dst):
buf = await src.read(1024)
while buf:
dst.write(buf)
await dst.drain()
buf = await src.read(1024)
async def handle(cmd, reader, writer):
print('Connection received')
PIPE = asyncio.subprocess.PIPE
process = await asyncio.create_subprocess_exec(*cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
await asyncio.gather(copy(reader, process.stdin),
copy(process.stdout, writer),
copy(process.stderr, writer))
async def start(host, port, cmd):
server = await asyncio.start_server(lambda r, w: handle(cmd, r, w), host, port)
async with server:
await server.serve_forever()
@click.command()
@click.option('-h', '--host', default='127.0.0.1', help='address to bind to')
@click.option('-p', '--port', default=31337, help='port to bind to')
@click.argument('cmd', nargs=-1)
def main(host, port, cmd):
"""Server that spawns a process for each new connection"""
asyncio.run(start(host, port, cmd))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment