May 4 Python Learning summary socketserver

Source: Internet
Author: User

First, Socketserver

Socketserver simplifies the writing of Web servers.

It has 4 classes: Tcpserver,udpserver,unixstreamserver,unixdatagramserver. These 4 classes are processed synchronously and are supported asynchronously through the Forkingmixin and ThreadingMixIn classes.

Steps to create a server:

1 . First, you must create a request processing class, which is a subclass of Baserequesthandler and overloads its handle () method.

2. Second, you must instantiate a server class, the address of the incoming server, and the request handler class.

3. Finally, call Handle_request () (usually call other event loops or use Select ()) or Serve_forever ().

When you integrate the ThreadingMixIn class, you need to handle exception shutdown. Daemon_threads indicates whether the server waits for thread termination, and if the threads are independent of each other, they must be set to TRUE and the default is False.

The server class has the same external methods and properties regardless of the network protocol.

The module has been renamed to Socketserver in Python3.

Server type

5 types: Baseserver,tcpserver,unixstreamserver,udpserver,unixdatagramserver. Note: Baseserver does not serve directly to the outside.

Server object
    • 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.

Instance:

Based on TCP:

ImportSocketserver#Communication CycleclassMytcphandler (socketserver. Baserequesthandler):defHahahahahahahh (self): whileTrue:Try: Data= SELF.REQUEST.RECV (1024)#1024 maximum limit of received data                if  notData Break  #for Linux SystemsSelf.request.send (Data.upper ())#Note: The sending and receiving are all in bytes units            exceptConnectionreseterror: Breakself.request.close ()if __name__=='__main__':    #Connecting LoopsServer=socketserver. Threadingtcpserver (('127.0.0.1', 8080), Mytcphandler) Server.serve_forever ()Print(server.server_address)Print(server. Requesthandlerclass)Print(Server.socket)#Conn,client_addr=sock.accpet ()#request, client_address = Self.get_request ()#self.process_request (conn, client_address)#self.finish_request (conn, client_address)#Obj=mytcphandler (conn,client_address,server)

Based on UDP:

ImportSocketserver#Communication CycleclassMyudphandler (socketserver. Baserequesthandler):defhandle (self):#print (self.request)res=Self.request[0]Print('data sent by the client:', res) self.request[1].sendto (Res.upper (), self.client_address)if __name__=='__main__':    #Connecting LoopsServer=socketserver. Threadingudpserver (('127.0.0.1', 8080), Myudphandler) Server.serve_forever ()

May 4 Python Learning summary 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.