I'm trying to make a simple proxy server in Python using the socket library, mostly to understand how it works. I'm a noob both at programming and networking, so please be nice if my questions are totally dumb.
At the moment I've set up a proxy server which intercepts requests from the browser, prints them and sends back an "Hello" sample response. It seems to work, so next I'm going to complete it by adding a client which forwards the request to the web server, receives the response and sends it back to the browser.
However, I have two doubts about this first (seemingly working) part of the code:
import socket, threading serv_port = 50007 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', serv_port)) server.listen(5) while True: #get conn to client conn, addr = server.accept() #span thread conn_thread = threading.Thread(target=cthread, args=(conn,)) conn_thread.start() def cthread(conn): #set timeout conn.settimeout(1) #receive data until null data is received or socket times out req = b'' while True: try: req_pack = conn.recv(4096) if not req_pack: break else: req += req_pack except socket.timeout: break print req #print request to stdout #send a sample response conn.send(b'HTTP/1.1 200 OK\n\n<h1>Hello</h1') #QUESTION 1 conn.close() #QUESTION 2
My first question is about threading. Should I leave everything as it is, or should I, after receiving a request, span a different thread to deal with the response part?
Sample code of what I mean:
#in function cthread print req #span thread resp_thread = threading.Thread(target=respthread, args=(conn, req)) resp_thread.start() def respthread(conn, req): #do everything that's to be done to get response, send it to browser conn.send(b'HTTP/1.1 200 OK\n\n<h1>Hello</h1') #sample response conn.close()
Another question: is it correct to close the connection to the browser (conn) after each response has been sent, or does it slow connections too much and it's possible to do without?