Python implements a simple Httpserver server

Source: Internet
Author: User
This article mainly introduces the Python implementation of a simple Httpserver server example, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

To write a simple server like Tomcat, you first need to figure out these points:

1. Role and role of the client and service side (Server)

Role a requests data to role B, at which point A is treated as a client and B as the server. The primary responsibility of the client is to send the request and the receiving service to return the requested information according to the request sent by the server, while the main responsibility of the server is to receive the request and return the request data.

2. What is the browser and how it works

We often say that the b/s,c/s architecture, the so-called B/s refers to browser/server,c/s refers to the CLIENT/SERVER,B/S architecture is actually applied to the browser program, as long as the last in the browser is displayed on the B/s architecture, rather than on the browser display is the C/s architecture , such as common League of Legends Games. But essentially only the C/s architecture, because the browser is a special client.

The special point of the browser is that there are three major engines:

    • Dom parsing engine: that is, the browser can parse the HTML

    • Style parsing engine: that is, the browser can parse the CSS

    • Script parsing engine: The browser can parse JavaScript

3. Socket

The above mentioned client service side, they are how to achieve connectivity and data transfer, this is the socket, each programming language has socket programming, the role of the socket is to provide the ability of network communication

4. HTTP protocol and the difference between HTTP and TCP/TP

The client and the server can realize the ability of network communication through socket, and realize data transfer. And the protocol is the standard data transmission, that is, the client and the server between the transmission of data to be in accordance with certain norms and standards of transmission, can not be passed blindly.

TCP/IP (transmission Control protocol/internet Protocol): Transmission protocol/Inter-network protocol

HTTP (Hypertext Transfer Protocol): Hypertext Transfer Protocol.

The difference between TCP/TP:

To make an image analogy, TCP/TP is the road, HTTP is the car on the road, so HTTP must be on the basis of TCP/TP.

HTTP is primarily applied to Web applications and is designed to provide a way to publish and receive HTML pages, which can be very abstract and difficult to understand. Specifically, when we visit a website, we only need to get content based on this site (such as Html,css,javascript). But we crawl the resource bundle that the browser receives (you can use the Fiddler tool) to discover the entity content that is required in addition to the Web page with the following information:

http/1.1 OK
Cache-control:private
Content-type:text/plain; Charset=utf-8
Content-encoding:gzip
Vary:accept-encoding
server:microsoft-iis/7.5
x-aspnet-version:4.0.30319
X-powered-by:asp.net
Date:tue, 03:25:23 GMT
Connection:close
content-length:661

This is the HTTP protocol specification, such as content-type means the format of the file at the time of transmission, content-encoding specifies the encoding format. More than these, very much, about the meaning of these parameters here is not to introduce

5. Meaning of the URL

URL (Uniform Resource Locator), is what we often say the URL, directly to parse a URL to explain him: http://198.2.17.25:8080/webapp/index.html

The implication is to find the IP 198.2.17.25 server under the directory WebApp index.html

But what we often see is this url:http://goodcandle.cnblogs.com/archive/2005/12/10/294652.aspx.

In fact, this is the same as above, but there is a domain name resolution, you can parse the goodcandle.cnblogs.com into the corresponding IP address

Figure out how to start writing code after five points.

webserver.py


Import Socketimport sysimport getfilecontent# declares an IP and port that will be bound, here is the local address server_address = (' localhost ', 8080) class WebServer ():  def run (self):    print >>sys.stderr, "Starting up" on%s port%s '% server_address    # Instantiate a socket    sock=socket.socket (socket.af_inet,socket. SOCK_STREAM)    #绑定IP和端口    sock.bind (server_address)    #设置监听    sock.listen (1)    #这里首先给个死循环, In fact, there is a need for multi-threading, and subsequent versions will implement while    True:      #接受客户端的请求并得到请求信息和请求的端口信息      connection, client_address = Sock.accept (      print >>sys.stderr, ' Waiting for a connection '      try:        #获取请求信息        data = CONNECTION.RECV (1024) C16/>if data:          #发送请求信息          connection.sendall (data)      finally:        Connection.close () if __name__ = = ' __main__ ':  server=webserver ()  Server.run ()

Webserver.py is clear and concise, the connection.sendall() server returns information to the browser, but the data sent must follow the HTTP protocol specification
Getfilecontent.py is the HTTP protocol specification processing of the transmitted data


Import sysimport os# Get data information to be sent Def gethtmlfile: msgsendtoclient= "" Requesttype=data[0:data.find ("/")].rstrip () #判断是GET请求还是POST请求 if requesttype== "GET": Msgsendtoclient=responsegetrequest (data,msgsendtoclient) if requesttype== " POST ": Msgsendtoclient=responsepostrequest (data,msgsendtoclient) return msgsendtoclient# Open file, not directly written here, The second is to fetch the file to be sent and then write Def getFile (msgsendtoclient,file): For line in File:msgsendtoclient+=line return msgsendtoclient# filter One way out of the request Def GETMIDSTR (data,startstr,endstr): StartIndex = Data.index (startstr) if startindex>=0:startindex + = Len (startstr) EndIndex = Data.index (ENDSTR) return Data[startindex:endindex] #获取要发送数据的大小, according to the HTTP protocol specification, to specify the size of the sent entity content in advance def G Etfilesize (FileObject): Fileobject.seek (0,2) size = Fileobject.tell () return size# set encoding format and file type Def setparaandcontext ( Msgsendtoclient,type,file,openfiletype): msgsendtoclient+= "Content-type:" +type+ "; Charset=utf-8" msgSendtoClient+ = "Content-length:" +str (GetFileSize (open (file, "R")) + "\ n" +"\ n" htmlfile=open (file,openfiletype) msgsendtoclient=getfile (msgsendtoclient,htmlfile) return msgSendtoClient# Return data for GET request Def responsegetrequest (data,msgsendtoclient): Return Responserequest (GETMIDSTR (data, ' GET/', ' http/1.1 '), msgsendtoclient) #POST请求的返回数据def responsepostrequest (data,msgsendtoclient): Return Responserequest (GETMIDSTR (data, ' POST/', ' http/1.1 '), msgsendtoclient) #请求返回数据def responserequest (getrequestpath,msgsendtoclient): Headfile=open (" Head.txt "," R ") Msgsendtoclient=getfile (msgsendtoclient,headfile) if getrequestpath==" ": msgsendtoclient= Setparaandcontext (msgsendtoclient, "text/html", "index.html", "R") Else:rootpath=getrequestpath if Os.path.exists (ro Otpath) and Os.path.isfile (RootPath): if ". html" in Rootpath:msgsendtoclient=setparaandcontext (Msgsendtoclien T, "text/html", RootPath, "R") if ". css" in Rootpath:msgsendtoclient=setparaandcontext (Msgsendtoclient, "text/css ", RootPath," R ") if". js "in Rootpath:msgsendtoclient=setParaandcontext (msgsendtoclient, "Application/x-javascript", RootPath, "R") if ". gif" in Rootpath:msgsendtoclient =setparaandcontext (msgsendtoclient, "Image/gif", RootPath, "RB") if ". Doc" in Rootpath:msgsendtoclient=setparaan Dcontext (msgsendtoclient, "Application/msword", RootPath, "RB") if ". mp4" in Rootpath:msgsendtoclient=setparaand Context (msgsendtoclient, "VIDEO/MPEG4", RootPath, "RB") Else:msgsendtoclient=setparaandcontext (Msgsendtoclient, " Application/x-javascript "," File.js "," R ") return Msgsendtoclient

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.