研究了一晚上的代码奉上:
#coding:utf-8
import socket
import re
# 定义一个常量用来接收客户端发起的文件请求地址
# 设置静态文件根目录
HTML_ROOT_DIR = "./html"
from multiprocessing import Process
def handle_client(client_socket):
"""处理客户端请求"""
# 获取客户端请求
request_data = client_socket.recv(1024)
print(request_data)
# 判断用户发来的请求
# 使用splitlines来切割不同行
request_lines = request_data.splitlines()
for line in request_lines:
print(line)
# GET / HTTP/1.1
request_start_line = request_lines[0]
file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
# 通常把常量写在“左边”,变量写在右边,防止少写一个“=”不报错
if "/" == file_name:
file_name = "/index.html"
# 打开文件,读取内容(客户有可能请求图片资源:加上b)
try:
file = open(HTML_ROOT_DIR + file_name, "rb")
except IOError:
response_start_line = "HTTP/1.1 404 NOT FOUND\r\n"
response_headers = "Sever: My Sever\r\n"
response_body = "The file is not found!"
else:
file_data = file.read()
file.close()
# 构造响应数据
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Sever: My Sever\r\n"
response_body = file_data.decode("utf-8")
response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response)
# 向客户端形响应数据
client_socket.send(bytes(response, "utf-8"))
# 关闭客户端连接
client_socket.close()
if __name__ == "__main__":
sever_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sever_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sever_socket.bind(("", 8090))
# 监听队列大小为128
sever_socket.listen(128)
# 为多个客户端服务
while True:
client_socket, client_address = sever_socket.accept()
print("[%s, %s]用户连接上了"%client_address)
handle_client_process = Process(target=handle_client, args = (client_socket,))
handle_client_process.start()
client_socket.close()
坑:没有把index.html放在“./html”里面,一直“not found”;要理解每一部分的含义,不能不求甚解
文件请求根目录
运行效果:
运行效果
网友评论