【问题标题】:How to create TCP proxy server with asyncio?如何使用 asyncio 创建 TCP 代理服务器?
【发布时间】:2017-09-25 20:44:44
【问题描述】:

我在 asyncio 上找到了这些带有 TCP 客户端和服务器的示例:tcp server example。但是如何连接它们以获得将接收数据并将其发送到其他地址的TCP代理服务器?

【问题讨论】:

    标签: python python-3.x asynchronous tcp python-asyncio


    【解决方案1】:

    您可以将the TCP client and server examplesuser documentation 结合起来。

    然后您需要使用这种帮助器将流连接在一起:

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

    这是一个可能的客户端处理程序:

    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()
    

    以及服务器代码:

    # 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()
    

    【讨论】:

    • 以及如何使用传输和 create_server/create_connection 创建这个代理?
    • 在打开与127.0.0.1:8889的连接之前,是否可以读取local_reader 以从实际请求中获取特定的标头值
    • @SreenadhTC 当然,在转发流量之前由客户端处理程序执行任何类型的操作。
    • @Vincent,嘿,是的,这就是我想要做的,但我遇到了一个问题。我在 SO here 上发布了相同的内容
    猜你喜欢
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多