import socket
import threading
import framework1
class Httpwebserver1(object):
def __init__(self):
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
tcp_server_socket.bind(('', 8080))
tcp_server_socket.listen(128)
self.tcp_server_socket = tcp_server_socket
@staticmethod
def handle_client_request(conn_server, ip_port):
client_request_data = conn_server.recv(1024).decode('utf-8')
print(client_request_data)
if len(client_request_data) > 0:
request_data = client_request_data.split('\r\n')
request_line = request_data.pop(0)
request_line_data = request_line.split(' ')
request_header = {}
for header in request_data:
if header == '':
continue
key = header.split(':')[0]
value = header.split(':')[1]
request_header[key] = value
request_path = request_line_data[1]
request_query = request_path.split('?')
if len(request_query) > 1:
request_path = request_query[0]
query_str = request_query[1]
else:
query_str = None
requests = {
'request_path': request_path,
'query_str': query_str,
'header': request_header
}
env = {
'request_path': request_path,
'requests': requests,
'ip_port': ip_port
}
response_line = 'HTTP/1.1 200 OK\r\n'
response_header = 'Server:pwb\r\nAccess-Control-Allow-Credentials:true\r\nAccess-Control-Allow-Origin:*\r\nAccess-Control-Allow-Methods:GET, POST, PUT\r\nAccess-Control-Allow-Headers:X-Custom-Header\r\n'
response_body = framework1.handle_request(env)
response_data = (response_line + response_header + '\r\n' + response_body).encode('utf-8')
conn_server.send(response_data)
conn_server.close()
def start(self):
while True:
conn_server, ip_port = self.tcp_server_socket.accept()
sub_thread = threading.Thread(target=self.handle_client_request, args=(conn_server, ip_port))
sub_thread.setDaemon(True)
sub_thread.start()
if __name__ == '__main__':
web_server = Httpwebserver1()
web_server.start()