Created
April 12, 2019 15:03
-
-
Save anthonyclays/bd0c6b853eb2ad956d4eacf22928eb98 to your computer and use it in GitHub Desktop.
Simple server that runs a process for each client connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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