For educational purposes, and without any importance, I wanted to implement a script that could make simple HTTP requests and show the content of the answer at the console (in plain text). I have achieved it with this code:
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8080)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
message = 'GET /php.php HTTP/1.1\r\n'
message += 'Host: localhost:8080\r\n\r\n'
print >>sys.stderr, 'sending "%s"' % message
sock.sendall(message)
data = sock.recv(10000000)
print >>sys.stderr, 'received "%s"' % data
sock.close()
I just build the HTTP request, send it to the server, and wait for an answer.
Now comes the question: I do not know how to read the whole answer, I know there is a header that is "content-lengt" (let's assume it will always be there). How can I read all the content of the answer without having to do sock.recv (1000000000000000000)?