1 import socket 2 3 4 class MyServer: 5 def __init__(self, ip, port): 6 self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 7 self.socket.bind((ip,port)) # 绑定的IP和端口 8 self.socket.listen(128) 9 10 def run_forever(self): 11 while True: 12 client_cocket,client_addr = self.socket.accept() # 获取http请求head及来源地址 13 data = client_cocket.recv(1024).decode("utf8") # 对收到的信息解码 14 path = '' 15 if data: 16 print("data is {}".format(data)) 17 print('{}'.format(client_addr)) 18 path = data.splitlines()[0].split(" ")[1] 19 print("请求的路径是:{}".format(path)) 20 21 # response head 22 response_head = "HTTP/1.1 200 OK" 23 24 if path == '/login': 25 response_body = "this is login path" 26 elif path == "/logout": 27 response_body = "you will logout" 28 elif path == "/": 29 response_body = "welcome to index" 30 else: 31 response_head = "HTTP/1.1 400 page not fund" 32 response_body = "you want to get page is lossing" 33 34 response_head += " " # 注意每一行结尾都要有一个空行 35 response_head += "content-type: text/html; charset=UTF-8 " # 注意这里最后还要有一个空行 36 response_body += " " 37 38 response = head + response_body # 拼接响应报文 39 client_cocket.send(response.encode("utf8")) # 发送响应报文 40 41 server = MyServer("0.0.0.0",9090) # 0.0.0.0表示任何IP地址都可以请求到服务 42 server.run_forever()