Skip to content

Instantly share code, notes, and snippets.

@anthonyclays
Created April 12, 2019 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyclays/bd0c6b853eb2ad956d4eacf22928eb98 to your computer and use it in GitHub Desktop.
Save anthonyclays/bd0c6b853eb2ad956d4eacf22928eb98 to your computer and use it in GitHub Desktop.
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