我的客户端最初使用持久HTTP与我自己的服务器进行通信。我现在正在尝试在它们之间插入Web代理,因此理想情况下,代理将维护2个单独的持久连接,一个与客户端连接,另一个与服务器连接。我怎样才能创建一个python Web代理呢?到目前为止我只能创建一个非持久的,我如何扩展它以进行持久连接?</ p> 到目前为止
代码:
def main():
# host and port info.
host = '' # blank for localhost
port = 80
try:
# create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# associate the socket to host and port
s.bind((host, port))
# listenning
s.listen(BACKLOG)
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket:", message
sys.exit(1)
# get the connection from client
while 1:
print "Proxy running..."
conn, client_addr_port = s.accept()
# create a thread to handle request
thread.start_new_thread(proxy_thread, (conn, client_addr_port))
s.close()
def proxy_thread(conn, client_addr_port):
print "received something...creating new thread"
global threadcount
client_addr = client_addr_port[0]
client_port = client_addr_port[1]
# Check if this is an new video flow (assumption now is that 1 client has 1 video flow, and the video does not terminate)
if client_addr not in client_vid_flows:
print "New client detected", client_addr
client_vid_flows[client_addr] = 0 # Expand to save video rate
# ctrl_msg_timer(client_addr) # Start timer that sends a ctrl_msg to the switch at a certain frequency
with lock:
threadcount = threadcount + 1
print "Thread number:", threadcount
# get the request from browser
request_text = conn.recv(MAX_DATA_RECV)
request = HTTPRequest(request_text)
if not request:
sys.exit(1)
if request.error_code:
sys.exit(1)
host = request.headers['host']
port_pos = host.find(":") # find the port pos (if any)
if (port_pos==-1): # default port
webserver = host
port = 80
else: # specific port
webserver = host.split(":")[0]
port = host.split(":")[1]
print "Connect to: %s:%i" % (webserver, port)
try:
# create a socket to connect to the web server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webserver, port))
s.send(request_text) # send request to webserver
while 1:
# receive data from web server
data = s.recv(MAX_DATA_RECV)
print data
if (len(data) > 0):
# send to browser
conn.send(data)
print 'more to send, len(data)={}'.format(len(data))
else:
print 'end of send'
# s.close()
# conn.close()
except socket.error, (value, message):
if s:
s.close()
if conn:
conn.close()
print "Runtime Error:", message
sys.exit(1)
print "--------------------------------"
#********** END PROXY_THREAD ***********
if __name__ == '__main__':
main()
来自wireshark,我看到正在向代理发送请求数据包。但是,代理人并没有这么做。