为什么代码中有 double\r\n 而不是 \r\n

Why there is double\r\n instead of \r\n in the codes

来自 PY4E 的原始代码:

import socket
import time
HOST = 'data.pr4e.org'
PORT = 80
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((HOST, PORT))
mysock.sendall(b'GET http://data.pr4e.org/cover.jpg HTTP/1.0\n\n')
count = 0
picture = b""

while True:
    data = mysock.recv(5120)
    if (len(data) < 1): break
    time.sleep(0.25)
    count = count + len(data)
    print(len(data), count)
    picture = picture + data
mysock.close()

# Look for the end of the header (2 CRLF)
pos = picture.find(b"\r\n\r\n")
print('Header length', pos)
print(picture[:pos].decode())

# Skip past the header and save the picture data
picture = picture[pos+4:]
fhand = open("stuff.jpg", "wb")
fhand.write(picture)
fhand.close()

我的问题有点多:

what is the mean of picture=b''

这是将 picture 变量设置为一个空字节数组,稍后将添加到。

what is pos for?

pos = picture.find(b"\r\n\r\n") 中,代码正在寻找图片数据之前的 HTTP header 的结尾。

What is [pos+4:] in picture=picture[pos+4:] for?

上面的评论说明了,"Skips past the header"只是获取图片数据

How can I view the image?

在这两行中,

fhand = open("stuff.jpg", "wb")
fhand.write(picture)

图片已保存到标题为 stuff.jpg 的文件中,您应该可以在文件管理器中双击打开它。