Use Python to implement simple server functions and python to implement servers

Source: Internet
Author: User

Use Python to implement simple server functions and python to implement servers

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 use C or Java to write the same socket server, and the socket method in all languages is similar (Apache is the server implemented using C)

The Web framework is to write the server in advance. Cross-language frameworks are not supported. 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 quickly using dynamic languages (such as Python, Ruby or PHP, such as twitter and facebook, code is converted to highly efficient languages such as C and JAVA, so that the server can more efficiently face hundreds of millions of requests every day.

TCP/IP and socket

Socket is a method for inter-process communication. It is an upper-layer interface based on the network transmission protocol. There are many types of sockets, such as TCP or UDP (two network transmission protocols ). Among them, TCP socket is the most commonly used. TCP socket is similar to duplex PIPE. A process writes or reads text streams to one end of the socket, and another process can read or write data from the other end of the socket, the two processes for establishing socket communication can belong to two different computers respectively. You only need to connect them through the network link and communication protocol.

The TCP protocol provides some communication rules so that the above processes can be effectively implemented in the network environment. Duplex PIPE (duplex PIPE) exists in the same brain, so you do not have to distinguish the address of the computer where the two processes are located. The socket must contain the address information for network communication.

A socket contains four addresses: the IP address of the two computers and the port used by the two processes ). IP addresses are used to locate computers, while ports are used to locate processes (multiple processes can use different ports on one computer ).

TCP socket

We can use a computer as a server. The server opens its own port and passively waits for other computers to connect to our port. When other computers, as customers, actively use socket to connect to the server, the server starts to provide services to customers. In fact, the two have established two-way Unicom.

In Python, we use the socket package in the standard library for underlying socket programming.

First, we use the bind () method to assign a fixed address and port to the socket, and use the listen () method to passively listen to the port. When a customer tries to connect using the connect () method, the server uses accept () to accept the connection, thus establishing a connection socket:

Server. py

Import socket # AddressHOST = '2017. 0.0.1 'port = 8000 # Configure sockets = socket. socket (socket. AF_INET, socket. SOCK_STREAM) s. bind (HOST, PORT) # socket. socket () creates a socket object and indicates that the socket uses IPv4 (AF_INET, IP version 4) # and TCP protocol (SOCK_STREAM ). # 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: ', request) print ('connectedby', addr) # send messagereply = 'Yes' "3. * socket. the data transmitted by send must be bytes. It cannot be str. Encode and convert data when sending and receiving data. Modify as follows: s. sendall (request. encode () "" conn. sendall (reply. encode () # close connectionconn. close ()

Client. py

import socket# AddressHOST = '127.0.0.1'PORT = 8000request = 'can you hear me?'# configure sockets    = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))""" 

It seems that the data transmitted by 3. * socket. send must be bytes. It cannot be str. Encode and convert data when sending and receiving data. Modify: s. sendall (request. encode ())

"""# send messages.sendall(request.encode())# receive messagereply  = s.recv(1024)print ('reply is: ',reply)# close connections.close()

We can call the recv () method on both ends of the socket to receive information and call the sendall () method to send information. 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.

HTTP Server Based on TCP socket

You can use TCP socket to establish a connection between the two remote computers and then communicate with each other.
However, the socket transmission degree of freedom is too high, resulting in many security and compatibility problems. We often use some application-layer protocols (such as HTTP) to specify socket usage rules and the format of transmitted information.

HTTP uses the request-response method to use TCP socket.

The client sends a piece of text to the server as a request. After receiving the request, the server sends a piece of text to the client as a response.

After such a request-response transaction is completed, the TCP socket is discarded. The next request will create a new socket.

Request and response are essentially two texts, but the HTTP protocol has certain format requirements for both texts.

Httpserver. py

import socket# AddressHOST = ''PORT = 8000# Prepare HTTP responsetext_content = '''HTTP/1.x 200 OK Content-Type: text/html

Explanation

The server transmits one of text_content and pic_content to the customer based on the request as the response text.

The entire response is divided into three parts: start line, head, and body.

The starting line is the first line: HTTP/1.x 200 OK, which is actually divided into three segments by spaces, HTTP/1. x indicates the HTTP Version Used, 200 indicates the status code, and 200 indicates that the server normally receives and processes requests according to the HTTP protocol, OK is the status code for reading.

The header information follows the starting line, and there is an empty line between it and the subject. Text_content or pic_content contains only one line of header information. text_content indicates that the Type of Subject Information is html text: Content-Type: text/html.

The subject information is the content of an html or jpg file. (Note: For jpg files, we open them in 'rb' mode to be compatible with windows. In windows, jpg is considered as a binary file. In UNIX, you do not need to distinguish between text files and binary files .)

HttpClient. py

Client program, you can write it yourself. Of course, browsers are generally used as clients.

Requests are sent to the server by a client program. Although the request can be divided into three parts as response, the request format is different from 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 start line can be divided into three parts: The first part is the request method, the second part is the URL, and the third part is the HTTP Version. The request method can include GET, PUT, POST, DELETE, and HEAD. GET and POST are commonly used. GET requests the server to send resources to the customer, and POST requests the server to receive data from the customer. When we open a webpage, 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 (resources on the server or other places ). As shown in the preceding figure, test.jpg is the current directory of the front-end server.

According to the HTTP protocol, the server must perform certain operations according to the request. As we can see in the server program, our Python program first checks the request method, and then generates different response (text_content or pic_content) based on different URLs ). Then, the response is sent back to the client.

Test

The terminal runs the above Httpserver program as the server, and then opens a browser as the client. (If you have time, you can use Python to write a client. The principle is similar to the preceding TCP socket client program .)
Enter 127.0.0.1: 8000 in the address bar of the browser.

Use the browser's debugging function F12

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

After receiving the text_content, the browser finds that the HTML file of the text contains the text, the channel uses the text.jpg file to add it as an image, and immediately sends the second request:

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/

Summary

1) In our above server program, we use the while loop to keep the server working. In fact, the multi-thread knowledge is used to change the content in the while loop to multi-process or multi-thread work.

2) The server program is not complete yet, so that the Python program can call other functions of Python to implement more complex functions. For example, to create a time server, let the server return the date and time to the customer. You can also use the Python database to implement a complete LAMP server.

3) socket packages are relatively low-level packages. The Python standard library also contains high-level packages, such as SocketServer, SimpleHTTPServer, CGIHTTPServer, and cgi. These packages help us to use sockets more easily. These packages are easy to understand. With these high-level packages, you can write a very mature server.

4) after all the troubles, I found that the framework was so convenient, so I decided to use the framework. Of course, you can also participate in framework development enthusiasm.

Summary

The above section describes how to use Python to implement simple server functions. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.