10.python Network Programming (socket server implementation Concurrent Part 2)

Source: Internet
Author: User

First, the basic principle analysis of socket communication based on TCP.

TCP-based socket communication, mainly relies on two loops, respectively, is the connection cycle and the communication cycle.

This previous article has been written, here will not repeat.


Second, the Socketserver realizes the multi-concurrency principle analysis.

1.server class:

650) this.width=650; "style=" Margin:auto; "src=" http://images2015.cnblogs.com/blog/1036857/201705/ 1036857-20170505014200961-1776184607.png "alt=" 1036857-20170505014200961-1776184607.png "/>

2.reques class.

650) this.width=650; "style=" Margin:auto; "src=" http://images2015.cnblogs.com/blog/1036857/201705/ 1036857-20170505014309914-771361140.png "alt=" 1036857-20170505014309914-771361140.png "/>

Class inheritance Relationships:

650) this.width=650; "style=" Margin:auto; "src=" http://images2015.cnblogs.com/blog/1036857/201705/ 1036857-20170505015158101-334152905.png "alt=" 1036857-20170505015158101-334152905.png "/>


650) this.width=650; "style=" Margin:auto; "src=" http://images2015.cnblogs.com/blog/1036857/201705/ 1036857-20170505015356492-1711228984.png "alt=" 1036857-20170505015356492-1711228984.png "/>

Example code:

Import socketserverimport structimport jsonimport osclass ftpserver (Socketserver. Baserequesthandler):     coding= ' utf-8 '     server_dir= ' file_upload '     max_packet_size=1024    base_dir=os.path.dirname (Os.path.abspath (_ _file__))     def handle (self):         print ( Self.request)         while True:      &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;DATA=SELF.REQUEST.RECV (4)              data_len=struct.unpack (' i ', data) [0]        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;HEAD_JSON=SELF.REQUEST.RECV (Data_len). Decode (self.coding)              head_dic=json.loads (Head_json)           &nbSp;  # print (head_dic)              cmd=head_dic[' cmd ']            if hasattr ( Self,cmd):                 func =getattr (Self,cmd)                  func (head_dic)     def put (Self,args):         file_path = os.path.normpath (Os.path.join (             self. base_dir,            self.server_dir,             args[' filename ']         )         filesize = args[' filesize ']        recv_size = 0         print ('-----> ',  file_path)         with open ( file_path,  ' WB ')  as f:             while recv_size < filesize:           &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RECV_DATA&NBSP;=&NBSP;SELF.REQUEST.RECV (self.max_packet_size)                  f.write (Recv_data)                  recv_size +=  len (Recv_data)                  print (' recvsize:%s filesize:%s '  %  (recv_size, filesize)) Ftpserver=socketserver. Threadingtcpserver (' 127.0.0.1 ',8080), Ftpserver) Ftpserver.serve_forever () 

Analysis begins:

In conjunction with the above example, there is a class diagram to look at.

Ftpserver=socketserver. Threadingtcpserver ((' 127.0.0.1 ', 8080), Ftpserver) Ftpserver.serve_forever ()

Order of Lookup properties: Threadingtcpserver->threadingmixin->tcpserver->baseserver

    1. By threadingtcpserver This class, an Ftpserver object is instantiated.

      1.2 First from Threadingtcpserver This class find __init__ method, Socketserver source can see, it itself does not __init__ method, This is the time to look for the two parent classes inherited from Threadingtcpserver. From the source can be seen threadingtcpserver altogether inherited two parents, respectively is threadingmixin and TCPServer, wherein threadingmixin there is no __init__ method, Finally, the __init__ is found under TCPServer, at which point the __init__ method under TCPServer is executed.



The __init__ method under 1.3 TCPServer has done four things, respectively, the __init__ method under the Baseserver class is executed, the socket object is created, the IP address and port are bound ( Bind), and start listen monitoring.

The __init__ method under the Baseserver class has done two things, adding two attributes to the created object, namely Server_address and RequestHandler Class, where server_address is the server-bound IP address and port, Requesthandlerclass is the Ftpserver class we created earlier.

(The bind and listen operations were completed because Server_bind and server_active were executed)


The 2.serve_forever implements the connection loop.

2.1 said before, Ftpserver this object is created by the class Threadingtcpserver, so, by default Ftpserver the object itself, and threadingtcpserver this class is not serve_ Forever this method, still according to the above routines, read the source code, from the Threadingtcpserver inherited from the parent class to find, respectively, is threadingmixin and TCPServer, in these two parents are not found in the class, Then go to see ThreadingMixIn and TCPServer inherit the parent class .... The concept of inheritance order is not to be mentioned in this ..... Finally, the Serve_forever method was found in the baseserver.


2.2serve_forever performs Self._handle_request_noblock () and then executes request, client_address = Self.get_request () (Self.socket.accept () in TCPServer), then execute self.process_request (Request, client_address)

Find Process_request in ThreadingMixIn, turn on multithreading to handle concurrency, and execute Process_request_thread, execute self.finish_request (request, Client_ Address).


2.3 The above four parts completed the link loop, this section began to enter the processing of the communication section, found in the Baseserver finish_request, triggering our own definition of the class instantiation, to find the __init__ method, and our own definition of the class does not have the method, Then go to its parent class, which is baserequesthandler ....



Finally, a few steps to create a socketserver are summarized.

    1. First, you must create a request handler class by subclassing the Baserequesthandlerclass and overriding its handle () meth Od This method would process incoming requests.


First you must create a class that must be a subclass of Baserequesthandler, and this class must have a handle method, which is used to handle incoming requests.


2.Second, you must instantiate one of the server classes, passing it the server ' s address and the request handler class.

Next you have to instantiate a server class that, during instantiation, needs to pass in the service-side address and the class of the request handle.


3.Then Call the Handle_request () or Serve_forever () method of the server object to process one or many requests.

Then, execute the handle_request () or Serve_forever () method of the server object to process one or more requests.


4.Finally, call Server_close () to close the socket.

Finally, execute the Server_close () method to close the socket.



This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1923787

10.python Network Programming (socket server implementation Concurrent Part 2)

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.