In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to apply the original Python server". In the daily operation, I believe that many people have doubts about how to use the original Python server. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about how to use the original Python server. Next, please follow the editor to study!
In today's era of Python server frameworks (framework, such as Django, Twisted, web.py, etc.), it seems like a thankless and stupid way to write a server from the underlying socket. The meaning of the framework is to cover up the underlying details, provide a set of API that is more developer-friendly, and deal with layout issues such as MVC. The framework allows us to quickly build a prototype and mature Python server. However, the framework itself also depends on the underlying layer (such as socket). Understanding the underlying socket can not only help us make better use of the framework, but also let us understand how the framework is designed. Furthermore, if you have good knowledge of low-level socket programming and other system programming knowledge, you can design and develop your own framework. If you can start with the underlying socket, implement a complete Python server, support user-level protocols, and deal with problems such as MVC (Model-View-Control), multithreading (threading), and sort out a clear set of functions or classes that are presented to users as an interface (API), you are designing a framework.
The socket interface is actually a system call provided by the operating system. The use of socket is not limited to the Python language, you can write the same socket server in C or JAVA, and all languages use socket in a similar way (Apache is a server implemented in C). And you can't use frameworks across languages. The advantage of the framework is that it helps you deal with some details to achieve rapid development, but it is also limited by the performance of Python itself. We have seen that many successful websites are developed rapidly using dynamic languages (such as Python, Ruby or PHP, such as twitter and facebook). After the success of the website, the code is converted into more efficient languages such as C and JAVA, so that the server can face hundreds of millions of requests more efficiently. In such times, the importance of the bottom far outweighs the framework.
TCP/IP and socket
We need to have some understanding of network transmission, especially TCP/IP protocol and socket. Socket is a method of inter-process communication (refer to Linux inter-process communication). It is an upper interface based on network transport protocol. There are many types of socket, such as based on the TCP protocol or UDP protocol (two network transport protocols). Among them, TCP socket is the most commonly used. TCP socket is similar to a two-way pipeline (duplex PIPE) in that one process writes or reads a stream of text to one end of the socket, while the other process can read or write from the other end of the socket. In particular, the two processes that establish socket communication can belong to two different computers. The so-called TCP protocol provides some communication rules in order to effectively realize the above-mentioned inter-process communication process in the network environment. The two-way pipe (duplex PIPE) lives on the same computer, so it is not necessary to distinguish the address of the computer where the two processes are located, and the socket must contain address information in order to achieve network communication. A socket contains four address information: the IP address of two computers and the port (port) used by the two processes. IP addresses are used to locate computers, while port is used to locate processes (multiple processes on a computer can use different ports).
A network connected by TCP socket
TCP socket
On the Internet, we can use a computer as a server. The server opens its own port and passively waits for other computers to connect. When other computers, as clients, actively use socket to connect to the server, the server begins to provide services to the customer.
In Python, we use the socket package from the standard library for underlying socket programming.
First, on the server side, we use the bind () method to give socket a fixed address and port, and use the listen () method to passively listen on the port. When a customer tries to connect with the connect () method, the server uses accept () to accept the connection, thus establishing a connected socket:
# Written by Vamei# Server sideimport socket# AddressHOST =''PORT = 8000reply =' Yes'# Configure sockets = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s.bind ((HOST, PORT)) # passively wait, 3: maximum number of connections in the queues.listen (3) # accept and establish connectionconn, addr = s.accept () # receive messagerequest = conn.recv (1024) print 'request is:', requestprint 'Connected by', addr# send messageconn.sendall (reply) # close connectionconn.close ()
Socket.socket () creates a socket object and states that socket uses IPv4 (AF_INET,IP version 4) and the TCP protocol (SOCK_STREAM).
Then using another computer as the customer, we actively use the connect () method to search for the server-side IP address (in Linux, you can use $ifconfig to query your own IP address) and port, so that the customer can find the server and establish a connection:
# Written by Vamei# Client sideimport socket# AddressHOST = '172.20.202.155'PORT = 8000request =' can you hear me?'# configure sockets = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s.connect ((HOST, PORT)) # send messages.sendall (request) # receive messagereply = s.recv (1024) print 'reply is:', reply# close connections.close ()
In the above example, we can call the recv () method on both sides of the socket to receive the information and call the sendall () method to send the message. In this way, we can communicate between two processes on two computers. When the communication ends, we use the close () method to close the socket connection.
(if you don't have two computers to experiment with, you can also change the IP that the client IP wants to connect to "127.0.0.1", which is a special IP address to connect to the local host.)
HTTP server based on TCP socket
In the above example, we can already use TCP socket to establish a connection between two remote computers. However, the degree of freedom of socket transmission is too high, which brings many security and compatibility problems. We often use some application layer protocols (such as HTTP protocol) to specify the rules for the use of socket and the format of the information transmitted.
The HTTP protocol uses request-response (request-response) to use TCP socket. The client sends a piece of text to the server as request, and the server sends a piece of text as response to the client after receiving the request. After completing such a request-response transaction, TCP socket was abandoned. The next request will create a new socket. Request and response are essentially two texts, but the HTTP protocol has certain formatting requirements for both texts.
Request-response cycle
Now, let's write a HTTP server side:
HOST = = 8000text_content = f = open (, = pic_content + s = s.listen (3 steps = conn.recv (1024 = request.split (= request.split () [1 method = = src = =: content = conn.close () goes deep into the HTTP server program
As we saw above, the server transmits one of the two messages text_content and pic_content to the customer based on the request as the response text. The whole response is divided into three parts: the starting line (start line), the header information (head) and the body (body). The starting line is the first line:
HTTP/1.x 200 OK
It is actually divided into three segments by spaces. HTTP/1.x represents the version of HTTP used, 200represents status code, 200is specified by the HTTP protocol, indicating that the server receives and processes requests normally, and OK is a status code for people to read.
The header information follows the starting line, and there is a blank line between it and the body. The text_content or pic_content here have only one line of header information, and the type of text_content used to represent the body information is html text:
Content-Type: text/html
The header information of pic_content (Content-Type: image/jpg) indicates that the type of subject is jpg picture (image/jpg).
The body information is the content of the html or jpg file.
Note that for jpg files, we open them in 'rb' mode for compatibility with windows. Because under windows, jpg is considered a binary file, under UNIX, there is no need to distinguish between text files and binary files.)
We did not write the client program, we will use the browser as the client later. The request is sent to the server by the client program. Although request can be divided into three parts like response, the format of request is not the same as that of response. The request is sent to the server by the customer, for example, the following is a request:
GET / test.jpg HTTP/1.xAccept: text/*
The starting line can be divided into three parts, the first part is the request method (request method), the second part is URL, and the third part is the HTTP version. Request method can have GET, PUT, POST, DELETE, HEAD. The most commonly used are GET and POST. GET is to request the server to send resources to the customer, and POST is to request the server to receive the data sent by the customer. When we open a web page, we usually use the GET method; when we fill out the form and submit it, we usually use the POST method. The second part is URL, which usually points to a resource (a resource on the server or somewhere else). As it is now, it is the test.jpg that points to the current directory of the current server.
According to the HTTP protocol, the server needs to perform certain operations according to the request. As we can see in the server program, our Python program first examines the method of request and then generates a different response (text_content or pic_content) depending on the URL. The response is then sent back to the client.
Experiment with a browser
In order to cooperate with the server program above, I have saved a test.jpg image file in the folder where I placed the Python program. We run the above Python program on the terminal, as the server side, and then open a browser as the client. (if you have time, you can also write a client in Python. The principle is similar to the client program for TCP socket above.)
In the browser's address bar, enter:
127.0.0.1:8000
(of course, you can also use a computer and enter the IP address of the server.) I got the following results:
OK, I already have a server implemented in Python and written from socket.
From the terminal, we can see that the browser actually made two requests. The first request is (the key information is on the starting line, and the body of this request is empty):
GET / HTTP/1.1Host: 127.0.0.1:8000User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86: 64; rv:14.0) Gecko/20100101 Firefox/14.0.1Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip, deflateConnection: keep-alive
Our Python program sends the contents of the text_content to the server based on this request.
After receiving the text_content, the browser found that the html text of the body contains
Knowing that the text.jpg file needs to be obtained to supplement the picture, a second request is made immediately
GET / test.jpg HTTP/1.1Host: 127.0.0.1:8000User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86: 64; rv:14.0) Gecko/20100101 Firefox/14.0.1Accept: image/png,image/*;q=0.8,*/*;q=0.5Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip, deflateConnection: keep-aliveReferer: http://127.0.0.1:8000/
Our Python program analyzes the starting line and finds that / test.jpg meets the if condition, so it sends the pic_content to the customer.
Finally, the browser displays the html text and pictures in an appropriate way according to the syntax of the html language.
At this point, the study on "how to apply the original Python server" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.