我在 stackoverflow 提问了,暂时还没有人回复。网址在此。 https://stackoverflow.com/questions/56786505/when-i-created-a-socket5-proxy-server-using-asyncio-my-code-was-unexpectedly-bl
# -*- coding: utf-8 -*-
import asyncio
from struct import unpack, pack
async def handle_echo(reader, writer):
data = await reader.read(1024 * 64)
addr = writer.get_extra_info('peername')
print(f"connect from {addr!r}")
if len(data) < 3:
writer.close()
return
result = unpack('!BBB', data[:3])
writer.write(b'\x05\x00')
await writer.drain()
data = await reader.read(1024 * 64)
result = unpack('!4B', data[:4])
if result[0] == 5 and result[1] == 1 and result[3] == 3:
host_len = unpack('!B', data[4:5])[0]
host = data[5:host_len + 5].decode()
port = unpack('!H', data[host_len + 5:])[0]
print(f'len {host_len},host {host},port {port}')
try:
reader_remote, writer_remote = await asyncio.open_connection(host, port)
writer.write(pack('!5B', 5, 0, 0, 3, host_len) + host.encode() + pack('!H', port))
await writer.drain()
print(f'connect success !{host}')
except (TimeoutError, ConnectionRefusedError) as _:
print(f'connect failed !{host}')
writer.write(pack('!5B', 5, 3, 0, 3, host_len) + host.encode() + pack('!H', port))
await writer.drain()
writer.close()
return
while True:
client_data = await reader.read(1024 * 64)
print(f'{host} client->local {len(client_data)}')
if not client_data:
writer_remote.close()
writer.close()
print(f'{host} disconnect')
return
writer_remote.write(client_data)
await writer_remote.drain()
print(f'{host} local->remote !{len(client_data)}')
remote_data = await reader_remote.read(1024 * 64)
print(f'{host} remote->local! {len(remote_data)}')
writer.write(remote_data)
await writer.drain()
print(f'{host} local->client! {len(remote_data)}')
async def main():
server = await asyncio.start_server(
handle_echo, '0.0.0.0', 3333)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())
如果一个网页只有一个 html 的话就没问题,例如:example.com 。但是像 baidu.com 这种的要加载好多 js 和 css 的就不行了,打印几行日志就卡住了,应该是卡在这里,client_data = await reader.read(1024 * 64),不知道为什么。系统 win10,python3.7.3。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.