import socket def operation_request(client): recv= client.recv(1024) data = str(recv,encoding=‘utf8‘) request_header, request_body = data.split(‘\r\n\r\n‘) row = request_header.split(‘\r\n‘) method, url, protocal = row[0].split(‘ ‘) func = None for i in router: if url == i[0]: func = i[1] break if func: return func() else: return b‘404‘ def run(): # 服务端 s = socket.socket() # 创建 socket 对象 host = socket.gethostname() # 获取本地主机名 port = 12345 # 设置端口 s.bind((host, port)) # 绑定端口 s.listen(5) # 等待客户端连接 while True: c, addr = s.accept() # 建立客户端连接 response = operation_request(c) c.send(b‘HTTP/1.1 200 OK\r\n\r\n‘) c.send(response) c.close()
备注:本机建立的socket服务,本机浏览器访问可能会被拒绝,建议host改为本机的网络IP
原文:https://www.cnblogs.com/infinite-BKB/p/14866861.html