1.老师给的思路
#tcp socket 服务端 socket = socket.socket() socket.bind() socket.listen() client_socket = socket.accept() while True: p = Process(target=fun, args=()) p.start() client_socket.close() def fun(client_socket): #接受数据 #request_data = recv(1024) #print(request_data) #解析Http报文数据 request_data #提取请求方式 #提取请求路径path HTML_ROOT_DIR = "./html" path = /index.html /login.html try: file = open("index.html") data = file.read() file.close() except IOError: """ HTTP1.1 404 not found\r\n \r\n not found """ #返回相应数据 """ HTTP1.1 200 OK\r\n \r\n hello itcast """ #send() #close()
2)版本1:主进程程序
from socket import * from multiprocessing import Process def fun(client_socket): pass def main(): #tcp socket 服务端 server_socket = socket(AF_INET,SOCK_STREAM) server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #防止端口不能重复访问 server_socket.bind(("",7788)) server_socket.listen(10) client_socket = server_socket.accept() #等待接受电话 while True: p = Process(target=fun, args=(client_socket,)) p.start() client_socket.close() server_socket.close() if __name__ == "__main__": main()
3)版本2:获取http报文头
from socket import * from multiprocessing import Process def fun(client_socket,client_addr): #接受数据 #request_data = recv(1024) #print(request_data) request_data = client_socket.recv(1024) print("[%s]\n%s"%(client_addr,request_data)) #解析Http报文数据 request_data #提取请求方式 #提取请求路径path #返回相应数据 #send() #close() def main(): #tcp socket 服务端 server_socket = socket(AF_INET,SOCK_STREAM) server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #防止端口不能重复访问 server_socket.bind(("",8080)) server_socket.listen(10) while True: client_socket, client_addr = server_socket.accept() # 等待接受电话 p = Process(target=fun, args=(client_socket,client_addr,)) p.start() client_socket.close() server_socket.close() if __name__ == "__main__": main()
4)版本3:获取html的内容
from socket import * from multiprocessing import Process def fun(client_socket,client_addr): #接受数据 #request_data = recv(1024) #print(request_data) request_data = client_socket.recv(1024) print("[%s]\n%s"%(client_addr,request_data)) request_data = str(request_data) #解析Http报文数据 request_data #提取请求方式 print(request_data[2:5]) request_method = request_data[2:5] #提取请求路径path print(request_data[6:8]) #返回相应数据 error_data = """ HTTP1.1 404 not found\r\n \r\n not found """ #HTML_ROOT_DIR = "./html" #path = "index.html" if request_method == "GET": try: file = open("./html/index.html") data = file.read() print(data) file.close() except IOError: error_data #send() #close() def main(): #tcp socket 服务端 server_socket = socket(AF_INET,SOCK_STREAM) server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #防止端口不能重复访问 server_socket.bind(("",8080)) server_socket.listen(10) while True: client_socket, client_addr = server_socket.accept() # 等待接受电话 p = Process(target=fun, args=(client_socket,client_addr,)) p.start() client_socket.close() server_socket.close() if __name__ == "__main__": main()
时间: 2024-10-04 15:29:02