简单的HTTP服务器[2]
程序员文章站
2024-03-20 16:31:34
...
之前写的服务器只能返回同一个页面index.html
,修改后可以打开对应目录返回, 不过需要手动修改index.html
对应的目录.
"""
@author: Bre Athy
@contact: https://www.zhihu.com/people/you-yi-shi-de-hu-xi
@productware: PyCharm
@file: 简单http服务器2.py
@time: 2019/11/8 14:01
"""
import socket,re
def service_client(new_tcp_socket):
# 接收数据
recv_data=new_tcp_socket.recv(1024)
path=r"E:\__init__\Downloads\Compressed\mikutap (2)"
ret=re.match(r"GET (.*?) H",recv_data.decode('gbk'))
if not ret:print("客户端连接已断开")
else:
if ret.group(1)==r"/":
path+=r"\index.html"
else:path+=ret.group(1).replace("/","\\")
# 准备请求头
try:
response_headers = bytes("HTTP/1.1 200 OK\r\n\r\n", encoding='gbk')
with open(path,"rb")as fp:
response_headers+=fp.read()
except:
response_headers = bytes("HTTP/1.1 404 NotFound\r\n\r\n", encoding='gbk')
response_headers+=bytes("<h1>页面不在了哟<h1>",encoding='gbk')
new_tcp_socket.send(response_headers)
new_tcp_socket.close()
def main():
'接收客户端服务'
# 创建套接字
tcp_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定端口
tcp_server_socket.bind(("",7788))
# 准备监听
tcp_server_socket.listen()
while True:
# 等待连接
new_tcp_socket,client_addr=tcp_server_socket.accept()
# 服务
service_client(new_tcp_socket)
if __name__ == "__main__":
main()