python - 如何使用 asyncio 创建 TCP 代理服务器?

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

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

最佳答案

您可以将两者结合使用 the TCP client and server examples来自 user 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()

关于python - 如何使用 asyncio 创建 TCP 代理服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46413879/

相关文章:

python /Scapy : sniff only incoming packets

python - 如何在服务器端发出 Socket IO 事件

python - 使用 python requests-HTML 获取标签的父元素

javascript - 异步还是同步?我该如何处理这些API调用?

javascript - 在 IF 语句中使用异步函数的返回值

python - 缺少 com.apple.xbs 文件夹,如何获取它?

python - 多处理: fork 的缺点?

python - 正则表达式从任何地方排除任何数字

python - 使用 Python 在 Lambda 中自定义日志文件

c# - 如何检查异步 Web 服务调用的错误