用tcp写一个服务器,返回网络请求
import threading
import socket
class WebServe:
def __init__(self):
"""在python的初始化方法中,用 `self.变量`表示的是成员变量
"""
self.s_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.s_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
self.s_socket.bind(("",8181))
self.s_socket.listen(128)
#静态方法
@staticmethod
def res_data(c_client:socket.socket):
try :
recv_d = c_client.recv(100000).decode()
path = recv_d.split(" ")[1]
if path == "/":
path = "/index.html"
file = open("./res"+path,"rb")
r_data = file.read()
file.close
except Exception as e:
r_line = "HTTP/1.1 404 NOT FOUND\r\n"
r_header = "server:python\r\nauthor:lingshijun\r\n"
r_body = "file not found"
r_result = r_line+r_header+"\r\n"+r_body
c_client.send(r_result.encode())
else :
r_line = "HTTP/1.1 200 OK\r\n"
r_header = "server:python\r\nauthor:lingshijun\r\n"
r_result = (r_line+r_header+"\r\n").encode()+r_data
c_client.send(r_result)
c_client.close()
def start(self):
while 1:
c_client,_ = self.s_socket.accept()
program=threading.Thread(target=self.res_data,args=(c_client,))
program.start()
if __name__ == "__main__":
WebServe().start()
网友评论