HyperText Transport Protocol - HTTP
The HyperText Transport Protocol is described in the following document: http://www.w3.org/Protocols/rfc2616/rfc2616.txt This is a long and complex 176-page document with a lot of detail. If you find it interesting, feel free to read it all. But if you take a look around page 36 of RFC2616 you will find the syntax for the GET request. To request a document from a web server, we make a connection to the www.py4inf.com server on port 80, and then send a line of the form
GET http://www.py4inf.com/code/romeo.txt HTTP/1.0
where the second parameter is the web page we are requesting, and then we also send a blank line. The web server will respond with some header informationabout the document and a blank line followed by the document content.
//makes a connection to a web server and follows the rules of the HTTP protocol to requests a document and display what the server sends back.
1 import socket 2 mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 mysock.connect((‘www.py4inf.com‘,80)) 4 mysock.send(‘GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n‘) 5 while True: 6 data = mysock.recv(512) 7 if(len(data)<1): 8 break 9 print data 10 mysock.close()
OUTPUT:
HTTP/1.1 200 OK Date: Sat, 12 Dec 2015 14:22:51 GMT Server: Apache Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT ETag: "e103c2f4-a7-526172f5b5d89" Accept-Ranges: bytes Content-Length: 167 Cache-Control: max-age=604800, public Access-Control-Allow-Origin: * Access-Control-Allow-Headers: origin, x-requested-with, content-type Access-Control-Allow-Methods: GET Connection: close Content-Type: text/plain But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fai r sun and kill the envious moon Who is already sick and pale with grief
Description:
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.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 output starts with headers which the web server sends to describe the document. For example, the Content-Type header indicates 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
Python Networked programs (网络编程)
原文:http://www.cnblogs.com/peng-vfx/p/5042015.html