#coding:utf-8 ''' 2018-6-18 14:47:23 创建一个静态服务器访问指定页面 http://127.0.0.1:8000/ ''' import socket from multiprocessing import Process HTML_ROOT_DIR = "" def handle_client(client_socket): ''' 处理客户端请求''' # 获取客户端请求数据 request_data = client_socket.recv(1024) print("request_data:",request_data) # 构造相应数据 response_start_line = "HTTP/1.1 200 OK " response_headers = "Sever:My server " response_body = "hello itcast" response = response_start_line+response_headers+" "+response_body print("response data:",response) # 向客户端返回响应数据 client_socket.send(bytes(reponse,"utf-8")) # 关闭客户端连接 client_socket.close() def main(): #tcp socket 服务端 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_socket.bind(("",8003)) server_socket.listen(128) while True: client_socket,client_address = server_socket.accept() print("") #创建一个进程 handle_client_process = Process(target=handle_client,args=(client_socket,)) handle_client_process.start() client_socket.close() if __name__ == '__main__': main()
#coding:utf-8 ''' 2018-6-18 18:05:41 创建一个静态服务器访问指定页面 http://127.0.0.1:8000/index.html ''' import socket import re from multiprocessing import Process # 设置静态文件根目录 常量全大写 HTML_ROOT_DIR = "./html" def handle_client(client_socket): ''' 处理客户端请求''' # 获取客户端请求数据 request_data = client_socket.recv(1024) print("request_data:",request_data) request_lines = request_data.splitines() for line in request_lines: print(line) #解析请求报文 # 'GET?HTTP/1.1' request_start_line = request_lines[0] # 使用正则,拿到 index.html file_name = re.match(r"w+ +(/[^ ]*) ",request_start_line.decode(utf-8)).group(1) # 判断反过来写,防止少写一个等号 不可变的写在左边 if "/" == file_name: file_name ="/index.html" # 打开文件,读取内容 try: file = open(HTML_ROOT_DIR+file_name,"rb") except IOError: response_start_line ="HTTP/1.1 404 NOt Found " response_headers = "server: My Sever " response_body = "The file is not found!" else: file_data = file.read().decode("utf-8") file.close() # 构造相应数据 response_start_line = "HTTP/1.1 200 OK " response_headers = "Sever:My server " response_body = file_data finally: response = response_start_line+response_headers+" "+response_body print("response data:",response) # 向客户端返回响应数据 python3需要转换成字节 client_socket.send(bytes(reponse,"utf-8")) # 关闭客户端连接 client_socket.close() def main(): #tcp socket 服务端 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #设置socket参数 server_socket.setsockopt(socket.SOL_SOCKET,socket.SOL_REUSEADDR,1) server_socket.bind(("",8000)) server_socket.listen(128) while True: client_socket,client_address = server_socket.accept() print("") #创建一个进程 handle_client_process = Process(target=handle_client,args=(client_socket,)) handle_client_process.start() client_socket.close() if __name__ == '__main__': main()