"Python"--socketserver

Source: Internet
Author: User

Socketserver

The Socketserver server uses IO multiplexing and "multithreading" and "multi-process" internally to enable concurrent processing of multiple client requests. That is, when each client requests a connection to the server, the socket server is creating a "thread" or "process" dedicated to all requests from the current client.

One, Socketserver type

1, TCPServer

This is for the TCP protocol, which provides continuous data flow between the client and the server

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

2, Udpserver

For UDP protocols, not sequential packets, intermediate transmissions may be lost. The parameters passed in are the same as the tcpserver.

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

3, Unixstreamserver and Unixdatagramserver

This is rarely used in TCP and UDP classes, but sockets is used in the UNIX domain; the incoming parameters are the same as the tcpserver.

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

4, socketserver Several types of instance diagram:

Second, create the Socketserver step (: Here take TCPServer as an example)
    1. A request processing class must be created, and the class inherits Baserequesthandlerclass, and also overrides the handle () in the parent class.
    2. You must instantiate TCPServer, and pass the server IP and the request processing class you created in the first step to this TCPServer
    3. Next Tune Server.handle_request () (processing only one request) or server.serve_forever () (Processing multiple client requests, always executing)
    4. Call Server_close () to close the socket

Server-side code implementation:

Note:

1, the import module when the 3.x version is Socketserver 2.x version is Socketserver

2, the client all the interaction is completed inside the handler, each request comes over, its request will be assigned, its request processing rule is handle inside stipulation. The server receives the client's data as NULL, indicating that the client has been disconnected.

Import Socketserverclass MyServer (socketserver. Baserequesthandler):   # Inherits Baserequesthandler this base class    # rewrite handle    def handle (self): while            True:                try:                    Self.data = self.request.recv (1024x768)  # server accepts data                    print ("{0} write:". Format (Self.client_address[0]))  # Print Client address print                    (Self.data.decode ())                    Self.request.send (Self.data.upper ())  # Send the client the data in uppercase before sending it back                Except Connectionreseterror as E:   # catch Exception, this exception when the client disconnects the server, this will only be available in python3.0                    print ("Error:", e)                    Breakif __name__ = = "__main__":    HOST, PORT = "localhost", 9999    server = Socketserver. TCPServer (HOST, PORT, MyServer)  # each tcpserver is instantiated MyServer this class    server.serve_forever ()  # implements multiple links    server.server_close ()   # Close the socket server

Client:

Import socketclient = Socket.socket () client.connect (("localhost", 9999) while True:    cmd = input (">>>:"). Strip ()    if len (cmd) = = 0:continue    client.send (Cmd.encode ("Utf-8"))    Cmd_res = CLIENT.RECV (+)    print (Cmd_res.decode ("Utf-8")) Client.close ()

The above code demonstrates how socketsever is used, but the code does not implement multiple concurrency effects, if you want to implement multi-threaded or multi-threaded need to change the service-side code slightly, the client remains unchanged.

third, the realization of multi-process, multi-threaded several concurrent classes:
# Multi-Process class socketserver. Forkingtcpserverclass Socketserver. forkingudpserver# multithreaded Class Socketserver. Threadingtcpserverclass Socketserver. Threadingudpserver

1, Multi-process:

When instantiating TCPServer, this multithreaded approach is forkingtcpserver, but it doesn't work on windows and needs to be done on Linux because Windows and Linux handle multiple processes differently

Import Socketserverclass MyServer (socketserver. Baserequesthandler):   # Inherits Baserequesthandler this base class    # rewrite handle    def handle (self): while            True:                try:                    Self.data = self.request.recv (1024x768)  # server accepts data                    print ("{0} write:". Format (Self.client_address[0]))  # Print Client address print                    (Self.data.decode ())                    Self.request.send (Self.data.upper ())  # Send the client the data in uppercase before sending it back                Except Connectionreseterror as E:   # catch Exception, this exception when the client disconnects the server, this will only be available in python3.0                    print ("Error:", e)                    Breakif __name__ = = "__main__":    HOST, PORT = "localhost", 9999    server = Socketserver. Forkingtcpserver (HOST, PORT), MyServer)  # Instantiate Server.serve_forever () in Forkingtcpserver multithreaded mode  # Implementing multiple Links    Server.server_close ()   # Close the socket server

2. Multithreading:

When instantiating a tcpserver, this multithreaded approach is used threadingtcpserver (this common)

Import Socketserverclass MyServer (socketserver. Baserequesthandler):   # Inherits Baserequesthandler this base class    # rewrite handle    def handle (self): while            True:                try:                    Self.data = self.request.recv (1024x768)  # server accepts data                    print ("{0} write:". Format (Self.client_address[0]))  # Print Client address print                    (Self.data.decode ())                    Self.request.send (Self.data.upper ())  # Send the client the data in uppercase before sending it back                Except Connectionreseterror as E:   # catch Exception, this exception when the client disconnects the server, this will only be available in python3.0                    print ("Error:", e)                    Breakif __name__ = = "__main__":    HOST, PORT = "localhost", 9999    server = Socketserver. Threadingtcpserver (HOST, PORT), MyServer)  # Instantiate Server.serve_forever () in Threadingtcpserver multithreaded mode  # Implementing multiple Links    Server.server_close ()   # Close the socket server

3、socketserver.BaseServer的主要方法:

#class Socketserver.baseserver: This is a superclass of all 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.

#服务器类支持下面的类变量: baseserver.allow_reuse_address: Whether the server allows 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.



#下面方法可以被子类重载, they 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.

  

"Python"--socketserver

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.