Jan Bodnar
Jan Bodnar

Reputation: 11637

Python Socket HTTP 1.1 keep-alive for a HEAD request

For the HTTP 1.1 protocol, the connections are persistent (keep-alive). The client should send Connection:close header attribute to close the connection. In a Python program, this is the case for a GET request. However, a connection for a HEAD request is closed without the Connection:close header.

What is the issue?

I have also tested a Java version of a HEAD request, and the connection is persistent there.

Python program for a HEAD request:

#!/usr/bin/env python

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

    s.connect(("webcode.me" , 80))
    s.sendall(b"HEAD / HTTP/1.1\r\nHost: webcode.me\r\nAccept: text/html\r\n\r\n")
    print(str(s.recv(1024), 'utf-8'))

Python program for a GET request:

#!/usr/bin/env python

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

    s.connect(("webcode.me" , 80))
    s.sendall(b"GET / HTTP/1.1\r\nHost: webcode.me\r\nAccept: text/html\r\nConnection: close\r\n\r\n")
    # s.sendall(b"GET / HTTP/1.0\r\nHost: webcode.me\r\nAccept: text/html\r\n\r\n")

    while True:

        data = s.recv(512)

        if not data:
            break

        print(data.decode())

Upvotes: 0

Views: 1695

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123320

For the HTTP 1.1 protocol, the connections are persistent (keep-alive)

No, the connections can be persistent if the server also wants them to be persistent. The server might decide to close the connection immediately, 5 seconds after ... or even never by its own if the client signals support for persistence.

However, a connection for a HEAD request is closed without the Connection:close header.

It is your client which is closing the connection, not the server. Your client does a single recv and then it is done with the socket and the program. If one would modify the code to continue with recv until no more data can be read then (similar to your second program) then the client would hang since the server is waiting for the new request from the client.

Upvotes: 1

Related Questions