Python network programming (ii) implementing multi-threaded Asynchronous sockets program via ThreadingMixIn

Source: Internet
Author: User

Use the ThreadingMixIn class to share the state of an app between threads, and to avoid the complex operation of interprocess communication compared to using the Forkingmixin class.

The code is as Follows:

1 #!/usr/bin/python2 3 ImportOS4 ImportSocket5 ImportThreading6 ImportSocketserver7 8Server_host ='localhost'9Server_port =0TenBuf_size = 1024 one  a defclient (ip, port, message): -     """A client to test threading Mixin Server""" -Sock =Socket.socket (socket.af_inet, Socket. Sock_stream) the sock.connect ((ip, Port)) -     Try: - Sock.sendall (message) -Response =sock.recv (buf_size) +         Print "Client received:%s"%Response -     finally: + sock.close () a  at  - classThreadedtcprequesthandler (socketserver.baserequesthandler): -     """an Example of threaded TCP request Handler""" -     defHandle (self): -data = Self.request.recv (1024) -Current_thread =Threading.current_thread () inResponse ="%s:%s"%(current_thread.name, Data) - Self.request.sendall (response) to  + classthreadedtcpserver (socketserver.threadingmixin, socketserver.tcpserver): -     """nothing Add here, inherited everything from Parenets""" the     Pass *  $ if __name__=='__main__':Panax Notoginseng     #Run Server -Server =threadedtcpserver (server_host, server_port), threadedtcprequesthandler) theip, Port =server.server_address +      a     #start a thread with the server, one thread per request theServer_thread = Threading. Thread (target=Server.serve_forever) +     #Exit The server thread when the main thread exits -Server_thread.daemon =True $ Server_thread.start () $     Print "Server Loop running on thread:%s"%Server_thread.name -  -     #Run Clients theClient (ip, port,"Hello from Client1") -Client (ip, port,"Hello from Client2")WuyiClient (ip, port,"Hello from Client3") the  -     #Server Cleanup wu Server.shutdown () -    

Note that point 1, in the Write Threadedtcprequesthandler class method handle handle write in order to handler, the results after the execution of the program, the display server returned to the client information is empty, The reason is that the handle method is the class method of the Baserequesthandler class inherited by the Threadedtcprequesthandler class, because The default behavior of the handle method of the Baserequesthandler class is nothing, so overwrite the handle method to handle accepting client messages, handle client requests, and, if written as handler, call the parent class by default in the program Baserequesthandler the handle method, but did nothing, so the display server return information is Empty.

Requesthandler. Handle ( )

This function must does all of the work required to service a Request. The default implementation does Nothing. Several instance attributes is available to it; The request is available as self.request; The client address as self.client_address; And the server instance as self.server, in case it needs access to Per-server Information.

The type ofself.requestis different for datagram or stream services. For stream services,self.requestis a socket object; For datagram services,self.requestis a pair of string and Socket. however, This can is hidden by using the request handler subclassesStreamrequesthandlerOrDatagramrequesthandler, which override theSetup ()andFinish ()methods, and provideSelf.rfileandSelf.wfileAttributes.Self.rfileandSelf.wfileCan is read or written, respectively, to get the request data or return data to the Client.

Note that point 2,with respect to the Setdaemon property of the thread object, True indicates that the server thread is a background thread, and when no activity is connected to the background thread, the program executes automatically exits, and when there is no active Non-background thread activity, the program exits Automatically. For this code, the specific behavior is that if the Setdaemon is true, the shutdown () of the server socket is not executed, the program executes as if it will automatically exit, and the Setdaemon state is false, then it must execute shutdown ( ), the program will automatically Terminate.

Python network programming (ii) implementing multi-threaded Asynchronous sockets program via ThreadingMixIn

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.