shrooms-server/shroom_pipe.py

33 lines
1.1 KiB
Python

import asyncio
import sys
# copied from https://stackoverflow.com/questions/64303607/python-asyncio-how-to-read-stdin-and-write-to-stdout
async def connect_stdin_stdout():
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await loop.connect_read_pipe(lambda: protocol, sys.stdin)
w_transport, w_protocol = await loop.connect_write_pipe(asyncio.streams.FlowControlMixin, sys.stdout)
writer = asyncio.StreamWriter(w_transport, w_protocol, reader, loop)
return reader, writer
async def pipe_loop(reader, writer):
while True:
#res = await reader.readline()
res = await reader.read(1024)
#res = await reader.readchunk()
if not res:
break
writer.write(res)
await writer.drain()
async def main():
reader, writer = await connect_stdin_stdout()
tcp_reader, tcp_writer = await asyncio.open_connection('localhost', 9876)
task_totcp = asyncio.create_task(pipe_loop(reader, tcp_writer))
task_fromtcp = asyncio.create_task(pipe_loop(tcp_reader, writer))
await asyncio.wait([task_totcp, task_fromtcp])
if __name__ == "__main__":
asyncio.run(main())