This article mainly introduces the simple HttpServer server example implemented in Python. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
To write a simple server similar to tomcat, you first need to understand these points:
1. Client (Client) and server The role and function of (Server)
Role A requests data from role B. At this time, A can be regarded as the client and B as the server. The main responsibility of the client is to send requests and receive request information returned by the server based on the requests it sends, while the main responsibility of the server is to receive requests and return request data.
2. What is a browser and how it works
We often talk about B/S, C/S architecture. The so-called B/S refers to browser/server, C /S refers to Client/Server. The B/S architecture is actually a program applied to the browser. As long as what is finally displayed on the browser is the B/S architecture instead of what is displayed on the browser is the C/S architecture. Such as the common League of Legends game. But essentially there is only a C/S architecture, because the browser is a special client.
The special thing about the browser is that it has the following three engines:
DOM parsing engine: that is, the browser can parse HTML
Style parsing engine: that is, the browser can parse CSS
Script parsing engine: that is, the browser can parse JAVASCRIPT
3. Socket
The client and server mentioned above, how to achieve connection and data transfer between them, this is Socket, every programming language has it Socket programming, the function of Socket is to provide the ability of network communication
4. HTTP protocol and the difference between HTTP and TCP/TP
The client and server use Socket Realizes the ability of network communication and can realize data transmission. The protocol regulates data transmission, which means that the data transmitted between the client and the server must be transmitted according to certain specifications and standards, and cannot be transmitted blindly.
TCP/IP (Transmission Control Protocol/Internet Protocol): Transmission Control Protocol/Internet Protocol
HTTP (HyperText Transfer Protocol): Hypertext Transfer Protocol.
The difference between TCP/TP:
To make a vivid metaphor, TCP/TP is the road, and HTTP is the car on the road. So HTTP must be based on TCP/TP.
HTTP is mainly used in web programs. It was originally designed to provide a method for publishing and receiving HTML pages. This may be very abstract and difficult to understand. Specifically, when we visit a website, we only need to get the content based on this website (such as html, css, JavaScript). But we grabbed the resource package received by the browser (you can use the Fiddler tool) and found that in addition to the entity content required by the web page, there is also some following information:
HTTP/1.1 200 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, 24 Jan 2017 03:25:23 GMT
Connection: close
Content-Length: 661
This is the http protocol specification. For example, Content-Type refers to the format of the file during transmission, and Content-Encoding specifies the encoding format. There are many more than the above. I will not introduce the meaning of these parameters one by one here
5. The meaning of URL
URL (Uniform Resource Locator) is The URL we often talk about is to directly parse a URL to illustrate it: http://198.2.17.25:8080/webapp/index.html
This means to find the server with the IP address 198.2.17.25 The lower directory is the index.html of the webapp
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 the above, but there is a domain name resolution here, which can resolve goodcandle.cnblogs.com into the corresponding IP address.
Start writing after clarifying the above five points. Code
webServer.py
import socket import sys import getFileContent #声明一个将要绑定的IP和端口,这里是用本地地址 server_address = ('localhost', 8080) class WebServer(): def run(self): print >>sys.stderr, 'starting up on %s port %s' % server_address #实例化一个Socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #绑定IP和端口 sock.bind(server_address) #设置监听 sock.listen(1) #这里首先给个死循环,其实这里是需要多线程的,再后续版本将会实现 while True: #接受客户端的请求并得到请求信息和请求的端口信息 connection, client_address = sock.accept() print >>sys.stderr, 'waiting for a connection' try: #获取请求信息 data = connection.recv(1024) if data: #发送请求信息 connection.sendall(getFileContent.getHtmlFile(data)) finally: connection.close() if __name__ == '__main__': server=WebServer() server.run()
webServer.py is very clear and concise,connection.sendall()
The server returns information to the browser server, but the data sent must comply with the HTTP protocol specification
getFileContent.py is to process the HTTP protocol specification for the sent data
import sys import os #得到要发送的数据信息 def getHtmlFile(data): 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 #打开文件,这里不直接写,二是去取要发送的文件再写 def getFile(msgSendtoClient,file): for line in file: msgSendtoClient+=line return msgSendtoClient #筛选出请求的一个方法 def getMidStr(data,startStr,endStr): startIndex = data.index(startStr) if startIndex>=0: startIndex += len(startStr) endIndex = data.index(endStr) return data[startIndex:endIndex] #获取要发送数据的大小,根据HTTP协议规范,要提前指定发送的实体内容的大小 def getFileSize(fileobject): fileobject.seek(0,2) size = fileobject.tell() return size #设置编码格式和文件类型 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 #GET请求的返回数据 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(rootPath) and os.path.isfile(rootPath): if ".html" in rootPath: msgSendtoClient=setParaAndContext(msgSendtoClient,"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=setParaAndContext(msgSendtoClient,"application/msword",rootPath,"rb") if ".mp4" in rootPath: msgSendtoClient=setParaAndContext(msgSendtoClient,"video/mpeg4",rootPath,"rb") else: msgSendtoClient=setParaAndContext(msgSendtoClient,"application/x-javascript","file.js","r") return msgSendtoClient
The above is the detailed content of Python implements a simple HttpServer server. For more information, please follow other related articles on the PHP Chinese website!