-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_try.py
105 lines (90 loc) · 2.44 KB
/
server_try.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python3
import socket
import sys
import parser,req_checker, imp_func, response
import threading
HOST= '0.0.0.0'
PORT= 8080
if len(sys.argv) > 1:
HOST = sys.argv[1]
if len(sys.argv) > 2:
PORT = int(sys.argv[2])
def req_handler(parsed_dic,orignal_msg):
req=parsed_dic["req"]
connection='close'
loc,ndic,content=None,None,None
if parsed_dic["bad_req"]:
sc=400
else:
#if parsed_dic["is_payload"]:
#parsed_dic["client_payload"]
#do something with client payload
sc, loc, ndic, content = req_checker.check_request(req)
#print(loc)
connection= imp_func.connect(req)
res = response.response_handler(sc, req, orignal_msg, connection, loc, ndic, content)
return res, connection, sc
def client_handler(conn,addr):
while True:
try:
data = []
timeout=imp_func.main_dict['timeout']
conn.settimeout(timeout)
buf = conn.recv(5000)
n=0
#try:
while True:
print(buf)
data.append(buf)
#conn.settimeout(0.05)
buf = conn.recv(1024)
if buf==b'\r\n':
print(1)
n=+1
if n>=2:
break
print(2)
print(n)
# except socket.timeout as e:
# pass
data = b"".join(data)
while True:
#parsed_dic=dict(req=req, bad_req=BAD_R, is_payload=payload, client_payload=client_payload, is_residue=is_residue, residue=residue)
parsed_dic=parser.request_parser(data)
req=parsed_dic["req"]
res, connection, sc = req_handler(parsed_dic, data)
conn.sendall(res)
imp_func.log_dump(addr[0],req, sc, response.ld ,logfile=lfile)
if parsed_dic["is_residue"]:
data=parsed_dic["residue"]
else:
break
except socket.timeout as e:
connection='close'
res=response.res_object({'Content-Length':'0','Connection':connection}, 408, encode=True)
conn.sendall(res)
#except:
# pass
if connection == 'close':
conn.close()
break
if __name__ == "__main__":
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen()
print("Listening on " + HOST + ":" + str(PORT))
docroot = imp_func.docroot
log_path = imp_func.log_path
lfile=open(log_path,'a', buffering=1)
while True:
conn, addr = s.accept()
print('accepted', conn, 'from', addr)
client_thread=threading.Thread(target=client_handler, args= (conn, addr,))
client_thread.start()
print(threading.enumerate())
except KeyboardInterrupt:
s.close()
print("Server Socket Closed")
sys.exit()