TCP 服务器连接网页,根据网页不同的点击,返回不同的网页内容

import socket
import re


def main():
pass
#服务器tcp服务器对象
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


#设置我们的端口地址重用
tcp_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)


#绑定端口号
tcp_server.bind(("",6789))
#改成被动模式
tcp_server.listen(True)
#循环去处理客户请求
while True:
client,addr = tcp_server.accept()          #我这个是简单版的,也可以在这边加上多进程,线程那个,xie'cheng实现多任务
# print(addr)


#接收数据
data = client.recv(1024).decode()
head_lines = data.splitlines()
try:
print(head_lines[0])
#GET /index.html HTTP/1.1
#使用正则去获取地址
re_match = re.match(r'[^/]+(/[^ ]*)', head_lines[0])   
#判断是否匹配了      
if re_match: #匹配 了     
#如果是/那么去首页
if file_name == "/":
file_name = "/index.html"
except Exception as e:
print(e)  #工作中是记录到文件


#返回数据
#响应头
#空行
#响应体
try:
headers = "HTTP/1.1 200 OK\r\n"




#会根据不同的地址返回不的内容
#打开文件写读文件内容
with open("./html%s"%file_name,'rb') as f:   #这样写有一个好处,如果是图片就不会有问题
body = f.read() #读取文件
#上面一般是ui设计师给你提前写好的文件,你拿来用就可以了

# body = "show page is find!"


# content = headers +"\r\n" +body
content = headers +"\r\n"


# client.send(content.encode("utf-8"))
client.send(content.encode("utf-8"))
client.send(body)
except Exception as e:
print(e)
#返回一个404的正常显示的页面
head = "HTTP/1.1 404 NOT FIND\r\n"
body = "not find page!"
content = head + "\r\n" + body




client.send(content.encode("utf-8"))




#关闭客户端
client.close()
#关闭服务器
tcp_server.close()




if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/qq_41868948/article/details/79966782