获取 recv() 缓冲区的一部分
getting part of the recv() buffer
我有这段打印 http 服务器响应的代码,但现在我试图获取唯一的状态代码,并从那里做出决定。
喜欢 :
代码:200 - 打印正常
code: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())
我会按如下方式更改接收循环:提取第一行,将其拆分,将第二个单词解释为整数。
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)
我有这段打印 http 服务器响应的代码,但现在我试图获取唯一的状态代码,并从那里做出决定。 喜欢 :
代码:200 - 打印正常 code: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())
我会按如下方式更改接收循环:提取第一行,将其拆分,将第二个单词解释为整数。
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)