Python implements a simple HttpServer server
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

MinIO Object Storage: High-performance deployment under CentOS system MinIO is a high-performance, distributed object storage system developed based on the Go language, compatible with AmazonS3. It supports a variety of client languages, including Java, Python, JavaScript, and Go. This article will briefly introduce the installation and compatibility of MinIO on CentOS systems. CentOS version compatibility MinIO has been verified on multiple CentOS versions, including but not limited to: CentOS7.9: Provides a complete installation guide covering cluster configuration, environment preparation, configuration file settings, disk partitioning, and MinI

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
