Python 实现一个简单的web服务器
importre
importsocket
defservice_cilent(new_socket):
request=new_socket.recv(1024).decode("utf-8")
#Pythonsplitlines()按照行('\r','\r\n',\n')分隔,返回一个包含各行作为元素的列表,如果参数keepends为False,不包含换行符,如果为True,则保留换行符。
request_lines=request.splitlines()
print(request_lines)
file_name=""
ret=re.match(r"[^/]+(/[^]*)",request_lines[0])
ifret:
file_name=ret.group(1)
iffile_name=="/":
file_name="index.html"
try:
f=open(file_name,"rb")
except:
response="HTTP/1.1404NOTFOUND\r\n\r\n"
response+="------filenotfound-----"
new_socket.send(response.encode("utf-8"))
else:
#打开文件成功就读文件然后关闭文件指针
html_content=f.read()
f.close()
#准备发送给浏览器的数据---header
response="HTTP/1.1200OK\r\n\r\n"
#将responseheader发送给浏览器
new_socket.send(response.encode("utf-8"))
#将responsebody发送给浏览器
new_socket.send(html_content)
#关闭套接字
new_socket.close()
defmain():
#创建套接字
tcp_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#tcp_server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#绑定
tcp_server_socket.bind(("",7089))
#监听套接字
tcp_server_socket.listen(128)
whileTrue:
new_socket,cilent_addr=tcp_server_socket.accept()
service_cilent(new_socket)
#关闭监听套接字
tcp_server_socket.close()
if__name__=='__main__':
main()
以上就是Python实现一个简单的web服务器的详细内容,更多关于python实现web服务器的资料请关注毛票票其它相关文章!