Files
framer-autoreg/httpconn.py
T

38 lines
1.2 KiB
Python

import socket, threading
PORT = 8898
def pipe(a,b):
try:
while True:
d=a.recv(65536)
if not d: break
b.sendall(d)
except Exception: pass
finally:
for s in (a,b):
try: s.close()
except Exception: pass
def handle(c):
try:
buf=b''
while b'\r\n\r\n' not in buf:
d=c.recv(4096)
if not d: return
buf+=d
line=buf.split(b'\r\n')[0].decode()
if line.split()[0].upper()=='CONNECT':
hp=line.split()[1]; host,port=hp.rsplit(':',1)
r=socket.create_connection((host,int(port)),timeout=25)
c.sendall(b'HTTP/1.1 200 Connection established\r\n\r\n')
threading.Thread(target=pipe,args=(c,r),daemon=True).start()
pipe(r,c)
else:
c.close()
except Exception:
try: c.close()
except Exception: pass
srv=socket.socket(); srv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
srv.bind(('127.0.0.1',PORT)); srv.listen(128)
print('listening',PORT,flush=True)
while True:
c,_=srv.accept(); threading.Thread(target=handle,args=(c,),daemon=True).start()