Manipulating the Python basic learning log Day8-socketserver

Source: Internet
Author: User

One: Socketserver simplifies the writing of web Servers.

It has 4 classes: tcpserver,udpserver,unixstreamserver,unixdatagramserver.

These 4 classes are processed synchronously, in addition to the Forkingmixin and ThreadingMixIn classes to support asynchronous

socketserver. class TCPServer (server_address, requesthandlerclass, bind_and_activate=true)

socketserver. class UDPServer (server_address, requesthandlerclass, bind_and_activate=true)

socketserver. class UnixStreamServer (server_address, requesthandlerclass, bind_and_activate=true)

socketserver. class UnixDatagramServer (server_address, requesthandlerclass,bind_and_activate=true)

Classsocketserver.ForkingTCPServer

Classsocketserver.ForkingUDPServer

Classsocketserver.ThreadingTCPServer

Classsocketserver.ThreadingUDPServer

Two: There is an inheritance relationship between five classes

 +------------+| baseserver | +------------+ | v+-----------+ +------------------+| tcpserver |------->| unixstreamserver | +-----------+ +------------------+ | v+-----------+ +--------------------+| udpserver |------->| unixdatagramserver | +-----------+ +--------------------+           
Unixstreamserver inheritance-   tcpserver inheritance Baseserver
Inheritance Udpserver Inheritance TCPServer Inheritance Baseserver

Three: Use steps
1) You must create a request class yourself and inherit
BaseRequestHandler,并重构hanndle方法
2)你必须实例化TCPServer,并且传递server ip和上面创建的请求的类
3)调用handle_request()方法或者server_forever()方法,
handle_request,只处理一个请求,server_forever 处理N多请求
4)关闭call_server()
创建服务器的步骤。首先,你必须创建一个请求处理类,它是BaseRequestHandler的子类并重载其handle()方法。
其次,你必须实例化一个服务器类,传入服务器的地址和请求处理程序类。
最后,调用handle_request()(一般是调用其他事件循环或者使用select())或serve_forever()。



Four: Baseserver
    • Class Socketserver.baseserver: This is the superclass of all the server objects in the Module. It defines the interface, as described below, but most of the methods are not implemented and are refined in Subclasses.

    • Baseserver.fileno (): Returns the integer file descriptor of the server listener Socket. Typically used to pass to Select.select () to allow a process to monitor multiple Servers.

    • Baseserver.handle_request (): processes a single Request. Processing order: get_request (), verify_request (), process_request (). If the user provides the handle () method throws an exception, the Server's handle_error () method is Called. If no request is received within the self.timeout, the Handle_timeout () is called and the Handle_request () is Returned.

    • Baseserver.serve_forever (poll_interval=0.5): processes the request until an explicit shutdown () request is Made. Polls every poll_interval seconds for Shutdown. Ignore Self.timeout. If you need to do periodic tasks, it is recommended to place them on other THREADS.

    • Baseserver.shutdown (): tells the Serve_forever () loop to stop and wait for it to Stop. python2.6 Version.

    • Baseserver.address_family: address families, such as socket.af_inet and Socket.af_unix.

    • Baseserver.requesthandlerclass: a user-supplied request processing class that creates an instance for each Request.

    • Baseserver.server_address: the address on which the server listens. The format varies according to the protocol family address, see the documentation for the socket MODULE.

    • Baseserver.socketsocket: the server on the server that listens for incoming requests to the socket Object.

The server class supports the following class Variables:

    • Baseserver.allow_reuse_address: whether the server allows the reuse of Addresses. The default is false and can be changed in Subclasses.

    • Baseserver.request_queue_size

The size of the request Queue. If a single request takes a long time to process, the server is busy when the request is placed in the queue, up to a maximum of request_queue_size. Once the queue is full, requests from the client will get a "Connection denied" Error. The default value is typically 5, but can be overridden by a quilt class.

    • Baseserver.socket_type: the type of socket used by the server; Socket. Sock_stream and Socket.sock_dgram and so On.

    • Baseserver.timeout: timeout, in seconds, or none means no Time-out. If Handle_request () does not receive a request within a timeout, handle_timeout () is Called.

The following methods can be overridden by subclasses, which have no effect on external users of server Objects.

    • Baseserver.finish_request (): actually handles the Requesthandlerclass initiated request and calls its handle () method. Common.

    • Baseserver.get_request (): accepts the socket request and returns a two-tuple containing the new socket object to be used for communication with the client, and the address of the Client.

    • Baseserver.handle_error (request, client_address): called if Requesthandlerclass's handle () method throws an Exception. The default action is to print Traceback to standard output and continue processing other Requests.

    • Baseserver.handle_timeout (): timed out Processing. By default, The forking server is a child process state that collects exits, and the threading server does Nothing.

    • Baseserver.process_request (request, client_address): Call Finish_request () to create an instance of Requesthandlerclass. If required, This feature can create new processes or threads to handle requests, which the Forkingmixin and ThreadingMixIn classes do. Common.

    • Baseserver.server_activate (): activates the server through the Server's Constructor. The default behavior is to listen only to the server Socket. Can be Overloaded.

    • Baseserver.server_bind (): binds the socket to the desired address by invoking the Server's Constructor. Can be Overloaded.

    • Baseserver.verify_request (request, client_address): Returns a Boolean value that, if true, will be processed and the request will be Rejected. This feature can be overridden to implement access control to the Server. The default implementation always returns True. The client_address can restrict the client, such as the request to handle only the specified IP range. Common.

Request processor

The processor receives the data and decides what to do. It is responsible for implementing protocols on top of the socket Layer (i.e., HTTP, xml-rpc, or AMQP), reading data, processing, and writing Reactions. The following methods can be overloaded:

    • Setup (): prepares request Processing. By default, Nothing is done, and Streamrequesthandler creates a File-like object to read and write to the Socket.

    • Handle (): Process the Request. Resolves incoming requests, processes data, and sends a response. Nothing is done by Default. Common Variables: Self.request,self.client_address,self.server.

    • Finish (): Environment Cleanup. Nothing is done by default, and if Setup produces an exception, the finish is not Executed.

typically, you only need to overload Handle. The type of self.request differs from the service of the datagram or Stream. For streaming services, Self.request is the socket object; for datagram services, self.request is a string and a socket. You can overload in subclasses Streamrequesthandler or datagramrequesthandler, rewrite setup () and finish (), and provide self.rfile and Self.wfile Properties. Self.rfile and Self.wfile can read or write to obtain the requested data or return the data to the Client.

Manipulating the Python basic learning log Day8-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.