[英]Python client socket can't recieve data from a successful response
Socket can't receive any data from the server, when there is a successful response, but with bad requests it can.当响应成功时,Socket 无法从服务器接收任何数据,但对于错误的请求,它可以。 Also server responds, just the socket can't receive data (checked in WireShark)
服务器也响应,只是套接字无法接收数据(在 WireShark 中检查)
import socket
import ssl
HOST, PORT = 'example.com', 443
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock = ssl.wrap_socket(sock)
ssock.connect((HOST, PORT))
raw_req = [f'GET / HTTP/1.1', 'Host: {HOST}', 'Connection: keep-alive']
req = '\n'.join(raw_req)
ssock.send(req.encode())
msg = ssock.recv(4096).decode()
print(msg)
ssock.close()
First, the HTTP GET expects two sequences of CR LF characters after the last header not just a single '\n' character.首先, HTTP GET期望在最后一个标头之后有两个 CR LF 字符序列,而不仅仅是一个 '\n' 字符。 Also, the join() adds the separator between each pair but not at the end so must append data with CR LF + CR LF to be a valid HTTP request.
此外,join() 在每对之间添加分隔符,但不是在末尾,因此必须使用 CR LF + CR LF 附加数据才能成为有效的 HTTP 请求。
Second, the 'Host: {HOST}'
must be a f-string otherwise the "{HOST}" is not replaced.其次,
'Host: {HOST}'
必须是 f 字符串,否则不会替换 "{HOST}"。
import socket
import ssl
HOST, PORT = 'stackoverflow.com', 443
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
ssock = ssl.wrap_socket(sock)
ssock.connect((HOST, PORT))
raw_req = [f'GET / HTTP/1.1', f'Host: {HOST}', 'Connection: keep-alive']
req = ('\r\n'.join(raw_req) + "\r\n\r\n").encode()
print("Request:", req)
ssock.send(req)
msg = ssock.recv(4096).decode()
print("\nResponse:")
print(msg)
Output:输出:
Request: b'GET / HTTP/1.1\r\nHost: stackoverflow.com\r\nConnection: keep-alive\r\n\r\n'
Response:
HTTP/1.1 200 OK
Connection: keep-alive
content-type: text/html; charset=utf-8
...
If the HTTP response is larger than 4096 bytes then you would need to call ssock.recv()
in a loop until it returns a byte array of length 0.如果 HTTP 响应大于 4096 字节,那么您需要在循环中调用
ssock.recv()
直到它返回一个长度为 0 的字节数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.