-
-
请教我的代理代码哪里出错了
-
发表于:
2013-7-19 15:49
4383
-
最近在接触python,尝试编写个简单的http代理服务器来学习,但是代码工作不正常,只能接收客户的数据,接收不到服务器返回的数据
import socket, _thread, select,http.client, io
class MyHandler:
def __init__(self, connection, address, timeout):
self.client = connection
self.timeout = timeout
self.host=''
self.port=80
data=self.HttpRequestParser()
self.remote = socket.create_connection((self.host, self.port))
self.remote.sendall(data)
self.Http_forward(self.client,self.remote)
self.remote.close()
self.client.close()
#连接建立后转发数据
def Http_forward(self,local, remote, timeout=60, ):
count = 0
while 1:
count += 2
(ins, _, errors) = select.select([ local,remote], [], [ local,remote], 2)
if errors:
break
if ins:
for sock in ins:
if sock is local:
remote.sendall(self.HttpRequestParser())
else:
local.sendall(sock.recv(8192))
count=0
else:
pass
if count == timeout:
break
#把来自客户端的请求重新封装下
def HttpRequestParser(self):
client_buffer = b''
while 1:
client_buffer += self.client.recv(8192)
end = client_buffer.find(b'\n')
if end!=-1:
break
end = client_buffer.find(b'\r\n')
method, path, protocol = (client_buffer[:end+1]).split()
client_buffer = client_buffer[end+2:]
end=client_buffer.find(b'\r\n\r\n')
postdata=client_buffer[end+4:]
headers=dict(http.client.parse_headers(io.BytesIO(client_buffer[:end+4])))
headers['Connection']='close'
path = path[7:]
i = path.find(b'/')
self.host = path[:i]
path = path[i:]
i = self.host.find(b':')
if i!=-1:
self.port = int(self.host[i+1:])
self.host = self.host[:i]
else:
self.port = 80
#重新构造http请求
data=method+b' '+path+b' '+protocol+b'\r\n'
data+=bytes(''.join('%s: %s\r\n' % (k, headers[k]) for k in headers if not k.startswith('Proxy-')), encoding = "utf-8") #herders
data+=postdata
print(bytes.decode(data))
return data
def start_server(host='localhost', port=8000, IPv6=False, timeout=60,
handler=MyHandler):
if IPv6==True:
soc_type=socket.AF_INET6
else:
soc_type=socket.AF_INET
soc = socket.socket(soc_type)
soc.bind((host, port))
print ("Serving on %s:%d."%(host, port))#debug
soc.listen(0)
while 1:
_thread.start_new_thread(handler, soc.accept()+(timeout,))
if __name__ == '__main__':
start_server()
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课