我有这段代码,它打印http服务器响应,但现在我试图获取唯一的状态代码,并从中做出决策。 比如:
代码:200-打印正常 代码:404-未找到打印页 等
PS:无法使用http库
from socket import *
#constants variables
target_host = 'localhost'
target_port = 80
target_dir = 'dashboard/index.html'
# create a socket object
client = socket(AF_INET, SOCK_STREAM) # create an INET (IPv4), STREAMing socket (TCP)
# connect the client
client.connect((target_host,target_port))
# send some data
request = "GET /%s HTTP/1.1\r\nHost:%s\r\n\r\n" % (target_dir, target_host)
#Send data to the socket.
client.send(request.encode())
# receive some data
data = b''
while True: #while data
buffer = client.recv(2048) #recieve a 2048 bytes data from socket
if not buffer: #no more data, break
break
data += buffer #concatenate buffer data
client.close() #close buffer
#display the response
print(data.decode())
我会如下更改接收循环:提取第一行,拆分它,将第二个字解释为整数
如果我们严重依赖
try
,我们可以简化第二部分相关问题 更多 >
编程相关推荐