使用Python构建我自己的代理服务器。客户端与代理之间以及服务器与代理之间的连接均成功。但是,例如,当我刷新网页时,使用recv()时不会得到任何数据。
class Proxy_server_connection(Thread):
def __init__(self, host, port):
super(Proxy_server_connection, self).__init__()
self.client = None
self.port = port
self.host = host
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.connect((host, port))
def run(self):
while True:
data = self.server.recv(4096)
print ("prox_server: ", data)
if data:
self.client.sendall(data)
class Proxy_client_connection(Thread):
def __init__(self, host,port):
super(Proxy_client_connection, self).__init__()
self.server = None
self.port = port
self.host = host
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
self.client, addr = s.accept()
def run(self):
while True:
data = self.client.recv(4096)
print ("prox_client: ", data)
if data:
self.server.sendall(data) #socket connected to real server
class Proxy(Thread):
def __init__(self, from_host, to_host, port):
super(Proxy, self).__init__()
self.from_host = from_host
self.to_host = to_host
self.port = port
def run(self):
while True:
print (("[proxy({})] setting up").format(self.port))
self.pc_connection = Proxy_client_connection(self.from_host, self.port)
#pick out url
data = self.pc_connection.client.recv(4096).decode()
host_word_len = 6
url_start = data.find("Host: ", 0, len(data)-1)
url_end = data.find("\r\n", url_start, len(data)-1)
url = data[url_start + host_word_len:url_end]
HTTP_PORT = 80
self.ps_connection = Proxy_server_connection(url, HTTP_PORT)
print(("[proxy({})] connection established").format(self.port))
self.pc_connection.server = self.ps_connection.server
self.ps_connection.client = self.pc_connection.client
self.pc_connection.start()
self.ps_connection.start()
master_server = Proxy('0.0.0.0', '127.0.0.1', 12345)
master_server.start()
当我启动代理并更新网页时,结果如下:
[proxy(12345)] setting up
[proxy(12345)] connection established
[proxy(12345)] setting up
(then it takes a couple of seconds in between)
prox_server: b''
prox_server: b''
prox_server: b''
etc.
因此由于某种原因,它从不接收任何数据,因此被困在Proxy_server_connection类的while循环中。这个代理我在做什么错了?