Network application (8): a package using the http

Http protocol spoken before, or how responsive appointment request line, header, body, also describes how to use the http request to complete the curl. This time, make persistent efforts, from a different angle change some of the roles that use http package and again. Anyway, only one purpose: to deepen the understanding of the http protocol.

Implement (1) tcp of

Http realization of said non-speaking tcp not (Why?'Ll explain later), while speaking before using tcp protocol, used in the socket, with the socket will be able to communicate, be able to do tcp want to do.

That socket is what?

Use your words to understand, socket is a channel do? Because it can communicate ah. "Socket is a channel" is already caught the key, though not complete, because the socket before becoming channel, the channel is not, it's just a wait value in use. However, the "focus" of abstraction is so important, not the pursuit of a complete or perfect. socket, the network nodes (ip: port), a data channel may represent, transfer data between nodes through it can. Imagine, all data exchanged on the network, completed by the socket.

socket is not just an abstract concept, it is a real code to achieve, but you can see is a binary code, which has been achieved to others, but also in various platforms, such as windows, unix, ios, android, etc. that it is in these platforms is what kind of existence? Who it is to achieve it?

Combined with information such as wiki pages:

Sockets originated in the University of California, Berkeley version of the Unix 20 1970, so that the socket is called "Berkeley sockets" or "BSD sockets." BSD sockets, socket is the ancestor of all other platforms, including windows / liunx, there are some languages ​​that use socket such as python, java and so on. bsd socket implemented c language, a corresponding layer c static library (or dynamic link library).

windows of the socket is Martin Hall, Mark Towfiq (belonging to Microsoft) and others of copyright, there are two major versions, winsock1 with winsock2, corresponding library file is wsock32.lib / ws2_32.lib, you're in the windows platform using this library file socket operation.

Well, some specific platform who wrote the realization of the socket, will not go into, but said, in gratitude for their contribution.

That question came, socket to achieve what?

tcp socket to achieve the agreement (also udp), this is very important, it is also important to http, because http located on the application layer in the protocol stack, depending on the tcp protocol transport layer, that is to say, the ultimate use http tcp to transmit data, including the implementation of tcp socket, you say that important?

So, http protocol relies on socket to transmit data, but also rely on rely on, does not mean http catechism things socket layer.

Implement (1) http of

http with different tcp, http is not concerned with how data is passed around, anyway, to pass on the line, this is a matter tcp layer, but also consider what it http? Is the format of requests and responses ah, but who can read the format, http request is very user-friendly, this dialogue has a very friendly (unlike tcp data). Introduced before the http message format!

For http request or response data, including lines, head, wherein the head line is indispensable. That form the first line of the body by whom the package, note that this is not the socket of things, regardless of the socket, then who cares?

Tools curl tube format http package (also pipe data transceiver), java's HttpClient tube format http package, python is also urllib tube format http package, there are many tools or libraries can be packaged http protocol (note that only http http the agreement does not include tcp, because tcp is another matter), of course, you write a package http format, there is no problem.

Briefly, http realized how things actually not include the transmission, it is a matter tcp layer (Socket), the focus is achieved http package and implement the protocol itself, such as how to assemble the first request, how to call data interface transceiver, how to interpret data, GET, or POST encapsulated, url encoding, and the like. You will find a lot of fragmented knowledge, a lot of business to achieve even went close, this is http is the performance of the application layer protocol.

For you, if not necessary, priority has been stable http package to achieve it, specifically to see what your platform for the corresponding options.

(2) use the http

When speaking before http structures with how to use curl, curl fact, by using http. Yes, we do not direct "use http", but rather by using http tools, you can write your own tools such as a httpclient get out of class, you can use some of the good performance of existing tools is recommended with the latter.

This time, some of the tools I use python libraries, such as urllib or httplib, through them using the http protocol.

General use http, that would like to request the server, that server how come? You can find a bunch of servers out naturally, as long as the corresponding url can, in fact, you just request a url. However, in order to appear high point, I am here to customize their own a web server for receiving http requests.

How to customize web server?

A small way in the use of presentation "PHP program," the lead came to the apache, apache is a web server, you can accept http request. On the other hand, apache can interact with PHP parser, python parsers, etc., according to http requests, execute some script code (like php script or python scripts, etc.).

Here show you, how to initiate a http request to apache, apache then execute python script that returns http response.

(A) can be enabled so that apache python

Before pressing explain knowledge, apache project directory is: / Library / WebServer / Documents, before the php script is placed here. However, python script, explaining it is cgi, cgi scripts to be placed in the project directory, the directory is: / Library / WebServer / CGI- Executables, so you write python scripts to be placed in this directory. To not Guannameduo in the CGI-Executables directory, create a hello.py, just write something like:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

title="小程"
info="你好,first py script,关注微信公众号'广州小程'"
htmlcontent="<html><head><meta charset='utf-8'><title>%s</title></head><body><h2>%s</h2></body></html>" % (title,info)
print("Content-type:text/html")
print("")
print(htmlcontent)

Then open the browser to request about this document it (note requesting cgi-bin directory), the result is this:
apache return script content

Obviously, this is not what I want to see it, I do not look at the script code, I want to see the contents of the script code is interpreted!

If the client such as a browser, to request a apache python or php script, apache but did not find the corresponding script interpreter, then (note apache themselves do not understand the script interpreter), the contents of the script apache will fully return to the browser , in which case the source exposed, it's probably not something you want to see.

So, let's find the apache script interpreter (here cgi), it is a crucial step.

Apache enabled no longer speak of a direct say, how to make apache run python script it? You may remember, let apache php calling program, then make apache configuration file httpd.conf change it (/ private / etc / apache2 directory), which is the "LoadModule phpx_module ..." uncomment this line, you can call php program, and that also is not python for this change? Yes, bingo, but also to lift the comment, this one is:

#LoadModule cgi_module libexec/apache2/mod_cgi.so

In front of the # removed and save what you can, pay attention to restart the apache:

sudo apachectl restart

At this time, apache will load mod_cgi.so, and used to explain the python cgi script. Then the browser requests once, to see such a return:
apache return the correct content

In simple terms, is used to explain the python cgi script, apache enable it to solve the problem of python script interpreter, cgi more things not to say.

(B) processing http request server

So far, apache can already execute a python script I wrote, that I wrote this hello.py what you do with it? Of course, dealing with the browser sent me the http requests. Therefore, the hello.py and change it to make it according to the parameter value of the request to return different content to the browser, such as this:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import cgi

title="广州小程"
info=""
paras = cgi.FieldStorage()
if paras.has_key('secret'):
    if paras['secret'].value=='free':
        info="<h1>welcome, you are so clever! secret is %s</h1>" % paras['secret'].value
    else:  
        info="<h1>wrong! secret is NOT '%s'</h>" % paras['secret'].value
else:
    info="<h1>NO! 请加上secret参数!</h1>"
htmlcontent="<html><head><meta charset='utf-8'><title>%s</title></head><body>%s</body></html>" % (title,info)
print("Content-type:text/html")
print("")

Script used cgi.FieldStorage get request parameters, this parameter gives different prompts. With a browser request it, pass different parameters, you can see this show:
When no secret parameters
Not when the secret Parameter
When the correct secret parameter

So far, everything is good, the script will be a good server can respond to the request, the browser also see the return of the contents, but, I do not teach you how to do web service ah, I want to say, how to use the http protocol ah!

(C) using the http protocol in python

This is the main focus. Demonstrated here to write a client in python inside the class, complete http request to indicate, I would have to use the http protocol!

Respectively, to demonstrate the use urllib2 with httplib.

import urllib2
url='http://localhost/cgi-bin/hello.py?secret=free'
req=urllib2.Request(url)
res=urllib2.urlopen(req)
res=res.read()
print(res)

Above code is executed, using the http protocol encapsulation urllib2 class, initiated the request, this is returned:
urllib2 response

import httplib
url='http://localhost/cgi-bin/hello.py?xx'
conn=httplib.HTTPConnection('localhost')
conn.request(method='GET', url=url)
res=conn.getresponse()
res=res.read()
conn.close()
print(res)

This piece of code on a lot of the image, first with HTTPConnection establish a link (with specified ip port, the port is omitted, the default means 80 that is the default web server port, and the other my localhost is fixed to the machine), and then initiate request , then take in response, one go. The results look like this:
httplib的响应

Get more requests are way, post is also very easy, you look at the thing. Well, already we will use the http protocol, or at least spend.

Summarize it, this article is mainly about how to use the http protocol, in order to understand that this operation, spoke with http tcp truths, but also talked about how to make apache explain python script, that last point is the key demo, you at least know that there urllib such a class can use the http protocol it!


what is import?

Guess you like

Origin www.cnblogs.com/freeself/p/11023564.html