The socketserver of Python

Source: Internet
Author: User

Socketserver Class Introduction

The socketserver module simplifies the task of writing network servers.

Socketserver There are so many different types

Class Socketserver. TCPServer (server_address, Requesthandlerclass, Bind_and_activate=true)

This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server.

Class Socketserver. Udpserver (server_address, Requesthandlerclass, Bind_and_activate=true)

This uses datagrams, which is discrete packets of information that may arrive out of order or is lost while in transit. The parameters is the same as for TCPServer .

Class Socketserver. Unixstreamserver (server_address, Requesthandlerclass, Bind_and_activate=true) class Socketserver. Unixdatagramserver (server_address, Requesthandlerclass,bind_and_activate=true)

These more infrequently used classes is similar to the TCP and UDP classes, but use Unix domain sockets; They ' re not available on Non-unix platforms. The parameters is the same as for TCPServer .

There is five classes in a inheritance diagram, four of the which represent synchronous servers of four types:

+------------+|  v+------------------+|    v+--------------------+|  +--------------------+
To create a socketserver step
    1. First, you must create a request handler class by subclassing the BaseRequestHandler class and overriding its handle() method; Would process incoming requests.
    2. Second, you must instantiate one of the server classes, passing it the server ' s address and the request handler class.
    3. Then call the handle_request() or serve_forever() method of the server object to process one or many requests.
    4. Finally, call to server_close() close the socket.
Basic Socketserver Instances
import socketserverclass Mytcphandler (socketserver.    Baserequesthandler): "" The request handler class for our server. It is instantiated once per connection to the server, and must override the handle () method to implement communication    to the client. "" "Def handle (self): # self.request is the TCP socket connected to the client Self.data = SELF.REQUEST.R  ECV (1024x768). Strip () print ("{} wrote:". Format (Self.client_address[0])) print (self.data) # Just send back The same data, but upper-cased Self.request.sendall (Self.data.upper ()) If __name__ = = "__main__": HOST, PORT = " LocalHost ", 9999 # Create the server, binding to localhost on port 9999 server = Socketserver. TCPServer (HOST, PORT), Mytcphandler) # Activate the server; This would keep running until you # interrupt the program with Ctrl-c Server.serve_forever () 

In this instance, the concurrent implementation of a multi-client connection cannot be implemented, and if you want your socketserver to be concurrent, you must choose to use one of the following multiple concurrency classes:

Classsocketserver.ForkingTCPServer

Classsocketserver.ForkingUDPServer

Classsocketserver.ThreadingTCPServer

Classsocketserver.ThreadingUDPServer

So just take the following sentence

Server = Socketserver. TCPServer (HOST, PORT), Mytcphandler)

In this case, it can be more concurrent, so that the client each in a connection, the server will be assigned a new thread to handle the client's request

Server = Socketserver. Threadingtcpserver (HOST, PORT), Mytcphandler)
Socketserver class method reference
Class Socketserver. Baseserver (server_address, Requesthandlerclass) This is the superclass of all servers objects in the module. It defines the interface, given below, but does isn't implement most of the methods, and which is do in subclasses. The parameters is stored in the respective server_address and Requesthandlerclass Attributes.fileno () Return an intege R file descriptor for the socket on which the server is listening. This function was most commonly passed to selectors, to allow monitoring multiple servers in the same process.handle_reques T () Process a single request. This function calls the following methods in Order:get_request (), Verify_request (), and Process_request (). If the user-provided handle () method of the handler class raises an exception, the server ' s Handle_error () method would be Called. If no request is received within timeout seconds, handle_timeout () would be called and handle_request () would return.serve_f Orever (poll_interval=0.5) Handle requests until an explicit ShuTdown () request. Poll for shutdown every poll_interval seconds. ignores the timeout attribute. It also calls Service_actions (), which May is used by a subclass or mixin to provide the actions specific to a given service. For example, the Forkingmixin class uses service_actions () to clean up zombie child processes. Changed in version 3.3:added service_actions call to the Serve_forever method.service_actions () this was called in the Serv E_forever () loop. This method can is overridden by subclasses or Mixin classes to perform actions specific to a given service, such as clean Up actions. New in version 3.3.shutdown ()-The Serve_forever () loop to stop and wait until it does.server_close () the Serve R. May is overridden.address_familythe family of protocols to which the server ' s socket belongs. Common examples is socket.af_inet and Socket.af_unix. Requesthandlerclassthe user-provided Request Handler class; An instance of this class are created for each request.server_addressthe address onwhich the server is listening. The format of addresses varies depending on the protocol family; See the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: (' 127.0.0.1 ', For Example.socketthe sockets object on which the server would listen for incoming requests. The server classes support the following class Variables:allow_reuse_addresswhether the server would allow the reuse of a Address.  This defaults to False, and can is set in subclasses to change the policy.request_queue_sizethe size of the request queue. If It takes a long time to process a single request, any requests this arrive while the server is busy be placed into a Queue, up to request_queue_size requests. Once the queue is full and further requests from clients would get a "Connection denied" error. The default value is usually 5, but this can be overridden by subclasses.socket_typethe type of socket used by the server; Socket. Sock_stream and socket. Sock_dgram is the common values.timeouttimeout duration, measured in seconds, or None if no timeout is desired. If handle_request () receives no incoming requests within the timeout period, the Handle_timeout () method is called. There is various server methods that can is overridden by subclasses of the base server classes like TCPServer; These methods aren ' t useful to external users of the server object.finish_request () actually processes the request by Insta Ntiating Requesthandlerclass and calling its handle () Method.get_request () must accept a request from the socket, and retur n a 2-tuple containing the new socket object to being used to communicate with the client, and the client ' s Address.handle_er Ror (Request, client_address) This function was called if the handle () method of a Requesthandlerclass instance raises an exc Eption. The default action is to print the Traceback to standard output and continue handling further requests.handle_timeout () Thi s function is Called when the timeout attribute have been set to a value other than None and the timeout period have passed with no Reque STS being received. The default action for forking servers are to collect the status of any child processes that has exited, while in Threadin  G Servers This method does Nothing.process_request (request, client_address) Calls finish_request () to the Create an instance of The Requesthandlerclass. If desired, this function can create a new process or thread to handle the request; The Forkingmixin and ThreadingMixIn classes do this.server_activate () called by the server's constructor to activate the SE RVer. The default behavior for a TCP server just invokes listen () on the server ' s socket. May is overridden.server_bind () called by the server's constructor to bind the socket to the desired address. May be overridden.verify_request (request, client_address) must return a Boolean value; If the value is True, the request would be processed, and if it ' s False, the request would be DenieD. This function can is overridden to implement access controls for a server. The default implementation always returns TRUE.

The socketserver of Python

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.