import ssl
import socket
ssl_context = ssl.create_default_context()
target = 'swapi.co'
port = 443
resource = '/api/people/1/'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
secure_client = ssl_context.wrap_socket(client, server_hostname=target)
send_str = 'GET {} HTTP/1.1\r\nHost: {}:{}\r\n\r\n'.format(resource, target, str(port))
secure_client.connect((target, port))
secure_client.send(send_str.encode())
print(send_str)
print(len(secure_client.recv(8192))) # 1282
print(len(secure_client.recv(8192))) # 5. Why?
Above is a simple Python program that sends an HTTP request to Star Wars API using TCP sockets.
This is the request sent:
GET /api/people/1/ HTTP/1.1
Host: swapi.co:443
The response header has Transfer-Encoding: chunked
in it. When the first recv is executed the header and the first chunk is obtained. However, to get the last chunk with terminator sequence ("0\r\n\r\n"), a second recv must be called. What is the underlying cause of this behavior?