Python-based socket Programming (III)

Source: Internet
Author: User

Python-based socket Programming (III)

What can be achieved with socket-based communication implemented earlier? In the TCP protocol communication is a user said a sentence, the service side to you back, you give the service side to say, the service side to give you back a sentence, so always friendly play down. And so on, another user came, he also want to and the service side of the exchange, so he sent a message to the server, after waiting for how long, and so do not know how much time, still did not wait until the service to give him the news, only when he can and server happy to play it? This will require the first user to exit and the server link, at this time the second client will be linked to the service side, at this moment, he can and service side happy play. Of course, some people will say, TCP does not want to do, that can use UDP to do, this can do, but, the data lost I want you to. So, what is this module that uses a Python-provided module to achieve the concurrency effect today? Yes, that's socketserver.

TCP-based sockets are essentially two loops, a loop that implements the connection, and a loop that communicates.

There are two main classes in the Socketserver module: the server class (troubleshooting link problems) and the request class (resolving communication problems).

The Socketserver internally uses IO multiplexing and "multithreading" and "multi-process" to enable the socket service side to process multiple client requests concurrently. 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. The bottom or socket is encapsulated and joined thread, the process is implemented Socketserver, the latter will be Socketserver source code analysis.

Take the following code as an example to analyze Socketserver Source:

1 F=socketserver. Threadingtcpserver (('127.0.0.1', 8080), MyServer)2 f.serve_forever ()

To find the order of attributes: Threadingtcpserver->threadingmixin->tcpserver->baseserver:

    1. Instantiate get F, first find class Threadingtcpserver __init__, found in TCPServer, and then execute server_bind,server_active
    2. Find Serve_forever under F, found in Baseserver, and execute Self._handle_request_noblock (), which is also in Baseserver
    3. Executes Self._handle_request_noblock () and then executes the request, client_address = Self.get_request () (which is self.socket.accept in TCPServer ( ), and then execute self.process_request (Request, client_address)
    4. Find Process_request in ThreadingMixIn, turn on multithreading to handle concurrency, and execute Process_request_thread, execute self.finish_request (request, Client_ Address
    5. 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 __init__ method, and our own definition of the class does not have the method, Then go to its parent class, which is baserequesthandler ....

SOURCE Analysis Summary:

TCP-based socketserver in our own defined class.

    1. Self.server is a Socket object
    2. Self.request is a link
    3. Self.client_address is the client address

UDP-based socketserver in our own defined class.

    1. Self.request is a tuple (the first element is the data sent by the client, the second part is the UDP socket object on the server), such as (b ' adsf ', <socket.socket fd=200, family= Addressfamily.af_inet, Type=socketkind.sock_dgram, proto=0, laddr= (' 127.0.0.1 ', 8080) >)
    2. Self.client_address is the client address

TCP-based Socketserver instances:

ImportSocketserverclassMyserver (socketserver. Baserequesthandler):defhandle (self):Print('Self :', self)Print('self.request:', Self.request) whileTrue:data= SELF.REQUEST.RECV (1024)            Print(data) Self.request.send (Data.upper ())#reply to the client by capitalizing all the words that were sent by the clientif __name__=='__main__': F= Socketserver. Threadingtcpserver (('127.0.0.1', 8080), Myserver) F.serve_forever ()
Service Side
Importsocketclient=Socket.socket (socket.af_inet, socket. Sock_stream) Client.connect (('127.0.0.1', 8080)) whileTrue:#Communication Cyclemsg = input ('>>>:'). Strip ()if  notMsgContinueclient.send (Msg.encode ('Utf-8')) Data= CLIENT.RECV (1024)    Print(data) client.close ()
Client

So, that's all for today, and then we have to take care of the multi-user FTP small project.

Python-based socket Programming (III)

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.