我在 asyncio 上找到了这些 TCP 客户端和服务器的示例:TCP 服务器示例 https://docs.python.org/3/library/asyncio-protocol.html#tcp-echo-server-protocol。但是如何连接它们以获得TCP代理服务器来接收数据并将其发送到其他地址呢?
您可以将两者结合起来TCP 客户端和服务器示例 http://asyncio.readthedocs.io/en/latest/tcp_echo.html来自用户文档 http://asyncio.readthedocs.io.
然后,您需要使用这种助手将流连接在一起:
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)