本题做法:列出整体思路,再去优化。
import socket
# 创建socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('tlias3.boxuegu.com', 80))
# 拼接请求报文,模拟客户端发起请求
request_line = 'GET / HTTP/1.1\r\n'
request_head = 'Host: www.baidu.com\r\n'
request_head += 'Connection: close\r\n'
request_data = request_line + request_head + '\r\n'
client_socket.send(request_data.encode())
response_data = b''
while True:
# 循环接收数据,因为服务器的数据可以不是一次性发过来的
recv_data = client_socket.recv(1024)
if recv_data:
response_data += recv_data
# resp_date = resp_date + recv_data
else:
break
response_data = response_data.decode()
responses = response_data.split('\r\n\r\n',1)
for s in responses:
print(s)
client_socket.close()
有见解的朋友欢迎下方留言探讨!!!