您在這裡

TheWorld’s Simplest Web Browser

24 二月, 2015 - 10:44

Perhaps the easiest way to show how the HTTP protocol works is to write a very simple Python program that makes a connection to a web server and following the rules of the HTTP protocol, requests a document and displays what the server sends back.

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)mysock.connect(('www.py4inf.com', 80))mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

while True:    data = mysock.recv(512)    if ( len(data) < 1 ) :        break    print data

mysock.close()

First the program makes a connection to port 80 on the server www.py4inf.com. Since our program is playing the role of the “web browser” the HTTP protocol says we must send the GET command followed by a blank line.

media/image13.png

Once we send that blank line, we write a loop that receives data in 512 character chunks from the socket and prints the data out until there is no more data to read (i.e. the recv() returns an empty string).

The program produces the following output:

HTTP/1.1 200 OKDate: Sun, 14 Mar 2010 23:52:41 GMTServer: ApacheLast-Modified: Tue, 29 Dec 2009 01:31:22 GMTETag: "143c1b33-a7-4b395bea"Accept-Ranges: bytesContent-Length: 167Connection: closeContent-Type: text/plain

But soft what light through yonder window breaksIt is the east and Juliet is the sunArise fair sun and kill the envious moonWho is already sick and pale with grief

The output starts with headers which the web server sends to describe the document. For example, the Content-Type header indicated that the document is a plain text document (text/plain).

After the server sends us the headers, it adds a blank line to indicate the end of the headers and then sends the actual data of the file romeo.txt.

This example shows how to make a low-level network connection with sockets. Sockets can be used to communicate with a web server or with a mail server or many other kinds of servers. All that is needed is to find the document which describes the protocol and write the code to send and receive the data according to the protocol.

However, since the protocol that we use most commonly is the HTTP (i.e. the web) protocol, Python has a special library specifically designed to support the HTTP protocol for the retrieval of documents and data over the web.