为什么换行符\n前需要一个回车return\r?
Why we need a carriage return \r before the new line character \n?
在下面的代码中,HTTP 协议需要两个换行符,但是 \r 需要什么。为什么我们不能只加两个\n然后发送请求呢?
import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(("data.pr4e.org",80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode() # here
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) > 0:
print(data.decode())
else :
break
mysock.close()
因为这就是 the HTTP protocol is defined. More specifically, HTTP 1.0 defines a request like this:
Request = Simple-Request | Full-Request
Full-Request = Request-Line
*( General-Header
| Request-Header
| Entity-Header )
CRLF
[ Entity-Body ]
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Full-Request
,这是任何 HTTP 1.0 兼容客户端(简单请求是 HTTP 0.9 且已弃用)都应该使用的,需要有两个 CRLF
令牌(一个在 Request-Line
). CRLF
标记是两个字节 \r\n
。因此需要在您的示例中以 \r\n\r\n
.
结束字符串
此设计选择保留在 HTTP 1.1 中。
因为 HTTP 协议就是这样工作的。
The request/status line and headers must all end with (that
is, a carriage return followed by a line feed). The empty line must
consist of only and no other whitespace.
在下面的代码中,HTTP 协议需要两个换行符,但是 \r 需要什么。为什么我们不能只加两个\n然后发送请求呢?
import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(("data.pr4e.org",80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode() # here
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) > 0:
print(data.decode())
else :
break
mysock.close()
因为这就是 the HTTP protocol is defined. More specifically, HTTP 1.0 defines a request like this:
Request = Simple-Request | Full-Request
Full-Request = Request-Line
*( General-Header
| Request-Header
| Entity-Header )
CRLF
[ Entity-Body ]
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Full-Request
,这是任何 HTTP 1.0 兼容客户端(简单请求是 HTTP 0.9 且已弃用)都应该使用的,需要有两个 CRLF
令牌(一个在 Request-Line
). CRLF
标记是两个字节 \r\n
。因此需要在您的示例中以 \r\n\r\n
.
此设计选择保留在 HTTP 1.1 中。
因为 HTTP 协议就是这样工作的。
The request/status line and headers must all end with (that is, a carriage return followed by a line feed). The empty line must consist of only and no other whitespace.