Python--socketserver

Source: Internet
Author: User

In Python 2.x, the Socketserver module is named Socketserver. This module simplifies the process of creating a server.

The module has four main types, of which tcpserver and udpserver are commonly used.

1. TCPServer

2. Unixstreamserver, similar to TCPServer, provides socket connections for data streams, but is intended for use on UNIX platforms;

3. Udpserver

4. Unixdatagramserver, similar to Udpserver provides datagram-oriented socket connections, but is intended for use on UNIX platforms;

These four types process the request synchronously , which means that the next request is not processed until a request is complete, which is certainly not suitable for production environments, and a client connection may delay all execution. So this module also provides two ways to support asynchronous Processing:

Forkingmixin, for each client request to derive a new process to specialize in processing;

ThreadingMixIn, a new thread is derived for each client request to specialize in processing;

First, let's introduce the process of developing a multi-process/thread asynchronous server using the Socketserver module:

1. Create an appropriate service type, such as a multi-process server for TCP connections: forkingtcpserver

2. Create a request handling handle (ask handler) type, and this type of handle () method (similar to the callback function) will handle the incoming client request connection.

3. Instantiate the server, the address that the incoming server should bind to, and the handle class that handles the request

4. Call the handle_request () or serve_forever () method of the server instance to process the client request one or more times.

1. Build the appropriate server type

The main basic service types and two mixin types provided by the Socketserver module are described above, which is the raw material for constructing multi-threaded/Process servers suitable for demand. It is up to the programmer to use and use these two mixin types, using Python's multiple inheritance mechanism to provide a new approach to the instance by making the Mixin type the code base instead of the tool that initializes the instance.

For example, define a line program asynchronous server type that uses a TCP connection:

class Forkingtcpserver (Frokingmixin, TCPServer):
Pass

The multiple inheritance mechanism of Python ensures that the definition of the target type can be completed as long as the necessary parent class is inherited, without the need to add additional content.

2. Create a request handling handle class

The Socketserver module provides a Baserequesthandler type for customizing the handler type, as long as the custom handler type inherits from the Baserequesthandler and overwrite its handle () method. The handle () method defines how the client's request is handled, and the server simply encapsulates the many operational processes of the socket object and the management of processes, threads, and so on, and then calls the handle () method for each client request.

The Baserequesthandler type provides the following interfaces, which they can overwrite as needed:

(1). Baserequesthandler.setup ()

Function: Called before the handle () method, completing some initialization work, and doing nothing in the default case.

  

(2). Baserequesthandler.handle ()

Function: Complete all processing for each request and do nothing by default. The method can get some instance properties that can be used when implemented: self.request is the client's request, and for TCP, the property is a socket object, which, for UDP, is a two-tuple of strings and sockets. self.client_address is the address of the client socket, and self.server is the server instance.

Streamrequesthandler and Datagramrequesthandler can mask the difference between TCP and UDP connections self.request , Both redefine the setup () and finish () methods, providing uniform self.rfile and self.wfile properties for reading data from the client or sending data to the client.

(3). baserequesthandler.finish ()

Function: Called after the handle () method, completes some cleanup work, and does nothing in the default case. If the Setup () method throws an exception, the method is not called.

3. Instantiating the server

It is necessary to instantiate the server when the incoming server needs to bind the address, and on the other hand should pass in the custom handler type, and the server instance will call its handle () method for each client connection.

For example:

Server = Forkingtcpserver ((host, Port), Myrequesthandler)

4. How to call Server instance processing

The handle_request () method of the server instance and the Serve_forever () method are used for single processing or for processing requests, either directly in the script or by invoking them in a new process or thread , start the server:

Import== Threading. Thread (target = server.serve_forever)
Server_thread.start ()

Add:

The available properties, methods (actually all from their parent class Socketserver.baseserver ) provided by TCPServer, Udpserver in Socketserver are:

Property:

baseserver.address_family

Content: The address family of the server socket object, such as socket.af_inet , Socket.af_unix , and so on.

Baseserver.requesthandlerclass

Content: User-defined, passed to the server constructor handler type, the server creates an instance of that type for each request.

baseserver.server_address

Content: The server listens to the address, the specific form depends on the address family, such as Af_inet form ('127.0.0.1', and so on).

Baseserver.socket

Content: A socket object that the server listens on

baseserver.allow_reuse_address

Content: Whether to allow address reuse, the default is False, the subclass can be changed.

baseserver.request_queue_size

Content: The length of the request queue, once the number of requests waiting for the service reaches this limit, subsequent requests receive a "Connection denied" error, usually the value defaults to 5 and subclasses can overwrite.

  

Baseserver.socket_type

Content: The type of socket used by the server, such as a socket. Sock_stream and sockets. Sock_dgram .

Baseserver.timeout

Content: The server's timeout limit, if none, does not set a timeout, and if the handle_request () method does not get a request within the specified time frame, the handle_timeout () method is called.

Baseserver.fileno ()

Content: Returns the FD for the socket object used by the server, a typical usage is to pass the Select.select () method to allow monitoring of multiple servers in one process.

Method:

Baseserver.server_bind ()

Function: Called by the instance's constructor, binds the socket to the destination address and can overwrite.

baseserver.server_activate ()

Function: Called by the constructor of the instance, the listener server socket can be overwrite.

baseserver.handle_request ()

Action: Process a single request, calling the get_request () , verify_request () , and process_request ( ) methods sequentially, if the user-defined handle () method to throw an exception, call the Handle_error () method, call the handle_timeout () method if more than self.timeout seconds have not been requested, and then The Handle_request () method returns.

baseserver.get_request ()

Role: The user of the server object does not necessarily need to call the method directly, accepting a request from the socket. Returns a two-tuple, the first element of which is a new connected socket object, and the element is the address of the client.

baseserver.verify_request (Request, client_address)

Role: The user of the server object does not necessarily need to call the method directly. Returns a Boolean value that is true when the request is processed, false when the request is denied, and access control can be implemented for the server by overwrite the method. The default implementation always returns TRUE.

baseserver.process_request (Request, client_address)

Role: This method embodies the role of mixin, where it is possible to create a thread or process to handle a user's request, which is ultimately the method by calling Finish_request () to instantiate a user-defined handler instance for each request. It then casts the new thread or process to process the user's request.

baseserver.finish_request ()

Role: Instantiate a user-defined handler instance for each request and call its handle () method.

baseserver.handle_error (Request, client_address)

Function: This method is called when the handle () method of the user-defined handler instance throws an exception. The default work is to print traceback to standard output, and then continue processing the request.

baseserver.handle_timeout ()

Effect: When the timeout limit specified by the Self.timeout attribute is reached (not none), the request is not yet waiting. The default behavior of a multi-process server is to collect the state of all the child processes that have exited, and the multithreaded server does nothing by default.

baseserver.serve_forever (poll_interval=0.5)

Function: The request is processed until the shutdown () function is explicitly called, and every poll_interval (default 0.5) second polling the shutdown, the function ignores self.timeout .

Baseserver.shutdown ()

Function: Stop the serve_forever () loop until it stops.

Contact_me:darren_wang_a^t_outlook.com

Python--socketserver

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.