获取recv()缓冲区的一部分

2024-04-19 11:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这段代码,它打印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())

1条回答
网友
1楼 · 发布于 2024-04-19 11:29:08

我会如下更改接收循环:提取第一行,拆分它,将第二个字解释为整数

line = b''
while True:
    c = client.recv(1)
    if not c or c=='\n':
        break
    line += c

status = -1
line = line.split()
if len(line)>=2:
  try:
    status = int(line[1])
  except:
    pass
print(status)

如果我们严重依赖try,我们可以简化第二部分

try:
  status = int(line.split()[1])
except:
  status = -1
print(status)

相关问题 更多 >