import socket
import multiprocessing
import threading
# 定义一个函数专门用于收发消息
def handle_client_request(new_socket, ip_port):
recv_data = new_socket.recv(1024)
if recv_data:
recv_data = recv_data.decode('utf-8')
recv_list = recv_data.split(' ', maxsplit=2)
print(recv_list)
request_path = recv_list[1]
print(request_path)
if request_path == '/':
request_path = '/index.html'
# 根据用户请求返回对应的页面给客户端浏览器
try:
with open('html'+request_path, 'rb') as f:
data = f.read()
except:
# 文件未找到 返回404
response_line = 'HTTP/1.1 404 Not Found'
response_head = 'Server:PWB2.0\r\nContent-type:text/html;charset=utf-8\r\n'
response_body = '很抱歉,您要访问的资源不存在,404 Not Found'
# 返回数据
response_data = (response_line + response_head + '\r\n' + response_body).encode('utf-8')
new_socket.send(response_data)
else:
# 文件找到200
response_line = 'HTTP/1.1 200 OK'
response_head = 'Server:PWB2.0\r\n'
response_body = data
# 返回数据
response_data = (response_line + response_head + '\r\n').encode('utf-8') + response_body
new_socket.send(response_data)
finally:
new_socket.close()
# 定义程序执行入口
if __name__ == '__main__':
# 创建套接字对象
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 端口复用
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 绑定ip
tcp_server_socket.bind(('', 8700))
# 监听
tcp_server_socket.listen()
# 等待客户端连接
while True:
new_socket, ip_port = tcp_server_socket.accept()
# 多任务接收消息
# 发送消息
# 创建子线程
sub_thread = threading.Thread(target=handle_client_request, args=(new_socket, ip_port))
sub_thread.start()
08-19
1162
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)