-
Notifications
You must be signed in to change notification settings - Fork 0
/
08-one_process_thread_http_server.py
104 lines (84 loc) · 2.99 KB
/
08-one_process_thread_http_server.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
import socket
import re
import time
def service_client(new_socket):
"""为这个客户端返回数据"""
# 1.接受浏览器发送过来的请求,即http请求
# GET / HTTP/1.1
# ...
request = new_socket.recv(1024).decode('utf-8')
# print('>>>'*50)
# print(request)
request_lines = request.splitlines()
print('')
print('>'*20)
print(request_lines)
# GET /index.html HTTP/1.1
# get post put del
ret = re.match(r'[^/]+(/[^ ]*)', request_lines[0])
if ret:
file_name = ret.group(1)
print('*'*50,file_name)
if file_name == '/':
file_name = '/index.html'
# 2.返回http格式的数据给浏览器
try:
f = open('./html' + file_name, 'rb')
except:
response = 'HTTP/1.1 404 NOT FOUND\r\n'
response += '\r\n'
response += '-----file not found-----'
new_socket.send(response.encode('utf-8'))
else:
html_content = f.read()
f.close()
# 2.1 准备发送给浏览器的数据----header
response = 'HTTP/1.1 200 OK\r\n'
response += '\r\n'
# 2.2 准备发送给浏览器的数据----body
# response += '<h1>hahahahaha</h1>'
# 将response header 发送给浏览器
new_socket.send(response.encode('utf-8'))
# 将response body 发送给浏览器
new_socket.send(html_content)
# 关闭套接字
new_socket.close()
def main():
"""用来完成整体的控制"""
# 1.创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 2.绑定
tcp_server_socket.bind(('', 7890))
# 3.变为监听套接字
tcp_server_socket.listen(128)
tcp_server_socket.setblocking(False) # 设置套接字为非堵塞的方式
client_socket_list = list()
while True:
time.sleep(0.5)
try:
# 4.等待新客户端的链接
new_socket, client_addr = tcp_server_socket.accept()
except Exception as ret:
print('----没有新的客户端到来----')
else:
print('----只要没有产生异常,那么就意味着 来了一个新的客户端----')
new_socket.setblocking(False)
# 5.为这个客户端服务
client_socket_list.append(new_socket)
for client_socket in client_socket_list:
try:
recv_data = client_socket.recv(1024)
except Exception as ret:
print('----这个客户端没有发送数据----')
else:
if recv_data:
print('----客户端发送了数据----')
else:
client_socket.close()
client_socket_list.remove(client_socket)
print('----客户端已经关闭----')
# 关闭监听套接字
tcp_server_socket.close()
if __name__ == '__main__':
main()