-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
87 lines (76 loc) · 2.82 KB
/
server.py
File metadata and controls
87 lines (76 loc) · 2.82 KB
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
from http import client
import socketserver
import sys
import ssl
import util.templete_engine
from util.request import Request
from util.router import Router
from util.from_paths import add_paths as form_paths
from util.user_paths import add_paths
from util.static_paths import add_paths as other_paths
import util.websockets
class myTCPhandler(socketserver.BaseRequestHandler):
images = []
def __init__(self, request, client_address, server):
self.router= Router()
add_paths(self.router)
other_paths(self.router)
form_paths(self.router)
util.websockets.add_paths(self.router)
super().__init__(request, client_address, server)
ws_connections=[]
counter = 0
def generate_response(body: bytes, content_type: str, response_code: str):
response = b'HTTP/1.1 ' + response_code.encode()
response += b'\r\nContent-Length: ' + str(len(body)).encode()
response += b'\r\nContent-Type: ' + content_type.encode() + b'; charset=utf-8'
response += b'\r\nLocation: /'
response += b'\r\nX-Content-Type-Options: nosniff'
response += b'\r\n\r\n'
response += body
return response
def handle(self):
received_data=self.request.recv(1024)
if len(received_data)==0:
return
#read http headers
#buffer if needef
sys.stdout.flush()
sys.stderr.flush()
request= Request(received_data)
#if ws request
if(util.websockets.ws_upgrade(request,self)):
self.router.handle_request(request,self)
else:
data=received_data
bod=request.body
if(request.method=="POST"):
while(len(bod)<int(request.headers["Content-Length"])):
data+=self.request.recv(1024)
request= Request(data)
bod=request.body
request= Request(data)
print("\n\n")
sys.stdout.flush()
sys.stderr.flush()
self.router.handle_request(request, self)
sys.stdout.flush()
sys.stderr.flush()
#self.request.sendall("HTTP/1.1 200 OK\r\nContent-Length: 5\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nhello".encode())
if __name__ == "__main__":
host="0.0.0.0"
port=8000
secure = False
server=socketserver.ThreadingTCPServer((host,port), myTCPhandler)
print("Listening on port " + str(port))
sys.stdout.flush()
sys.stderr.flush()
if not secure:
server.serve_forever()
else:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain('cert.pem', 'private.key')
socket=server.socket
with ctx.wrap_socket(socket, server_side=True) as secure_socket:
server.sokcet = secure_socket
server.serve_forever()