8

I found these example with TCP client and server on asyncio: tcp server example. But how to connect them to get TCP proxy server which will be receive data and send it to other adress?

1 Answer 1

17

You can combine both the TCP client and server examples from the user documentation.

You then need to connect the streams together using this kind of helper:

async def pipe(reader, writer):
    try:
        while not reader.at_eof():
            writer.write(await reader.read(2048))
    finally:
        writer.close()

Here's a possible client handler:

async def handle_client(local_reader, local_writer):
    try:
        remote_reader, remote_writer = await asyncio.open_connection(
            '127.0.0.1', 8889)
        pipe1 = pipe(local_reader, remote_writer)
        pipe2 = pipe(remote_reader, local_writer)
        await asyncio.gather(pipe1, pipe2)
    finally:
        local_writer.close()

And the server code:

# Create the server
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_client, '127.0.0.1', 8888)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
Sign up to request clarification or add additional context in comments.

4 Comments

And how to create this proxy with transports and create_server/create_connection?
Would it be possible to read the local_reader to get a specific header value form the actual request before opening the connection to 127.0.0.1:8889
@SreenadhTC Definitely, it's up to the client handler to perform any kind of operation before forwarding the traffic.
@Vincent, Hey, Ya that is what I was trying to do, and I came up with an issue. I posted the same on SO here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.