Explanation of the entire communication process of the python select. select module,

Source: Internet
Author: User

Explanation of the entire communication process of the python select. select module,

To understand the select. select module, we mainly need to understand its parameters and its three return values.
The select () method receives and monitors three communication lists. The first is all input data, that is, external data, 2nd are monitoring and receiving all outgoing data and 3rd monitoring error messages

I have been searching for this select. select parameter on the Internet for explanation, but there is no such explanation. Ah... I analyzed it myself.
Readable, writable, predictional = select. select (inputs, outputs, inputs)

The first parameter is the socket on the server side, the second is the socket on the client side stored during running, and the third stores the error message.
The focus is on the return value. The first returned is a readable list, the second stores a writable list, and the third stores error information.
List.
This does not need to be further investigated. You can understand the code by yourself.
All the code about select. select on the internet is similar, but some cannot run or are incomplete. I re-wrote a program that can run and made a lot of comments to understand it.

Server:

# Coding: utf-8import selectimport socketimport Queuefrom time import sleep # Create a TCP/IPserver = socket. socket (socket. AF_INET, socket. SOCK_STREAM) server. setblocking (False) # Bind the socket to the portserver_address = ('localhost', 8090) print ('starting up on % s port % s' % server_address) server. bind (server_address) # Listen for incoming connectionsserver. listen (5) # Sockets from which we recommend CT to readinputs = [server] # Sockets to which we recommend CT to write # process the message to be sent outputs = [] # Outgoing message queues (socket: Queue) message_queues ={} while inputs: # Wait for at least one of the sockets to be ready for processing print ('Waiting for the next event') # Start the select listener, listen to servers in input_list
# Once the send and recv functions of socket are called, readable, writable, and predictional = select will be called again. select (inputs, outputs, inputs) # Handle inputs # cyclically determines whether a client is connected. When a client is connected, select triggers for s in readable: # determine whether the currently triggered object is a server object. When the triggered object is a server object, a new client is connected. # indicates that a new user is connected to if s is server: # A "readable" socket is ready to accept a connection, client_address = s. accept () print ('Connection from', client_address) # this I S connection not server connection. setblocking (0) # Add the client object to the listener list. When the client sends a message, select triggers inputs. append (connection) # Give the connection a queue for data we want to send # create a separate message Queue for the connected client to save the message message_queues [connection] = queue sent by the client. queue () else: # An old user sends a message and processes it. # As the server receives the client connection request when the client is connected, it adds the client to the listener list (input_list ), the client will trigger message sending # so determine whether the client object is triggered data = s. recv (1024) # The client is not disconnected if data! = '': # A readable client socket has data print ('stored ed" % s "from % s' % (data, s. getpeername () # Put the received message into the message queue of the corresponding socket Client. message_queues [s]. put (data) # Add output channel for response # put the socket that requires the reply operation into the output list, and let the select listener if s not in outputs: outputs. append (s) else: # the client is disconnected and the listener of the client is removed from the input list # Interpret empty result as closed connection print ('closing', client_address) # Stop listening for input on the connection if s in outputs: outputs. remove (s) inputs. remove (s) s. close () # Remove message queue # Remove the message queue del message_queues [s] # Handle outputs of the corresponding socket Client object # If no client request exists and no client sends the message, start to process the sent message list. Do you want to send a message? # store the client that sent the message for s in writable: try: # if there is a message in the message queue, get the message message_queue = message_queues.get (s) send_data = ''if message_queue is not None: send_data = message_queue.get_nowait () else: # print "has closed" lost t Queue is disconnected from the client. empty: # print "% s" % (s. getpeername () outputs. remove (s) else: # print "sending % s to % s" % (send_data, s. getpeername) # print "send something" if message_queue is not None: s. send (send_data) else: print "has closed" # del message_queues [s] # writable. remove (s) # print "Client % s disconnected" % (client_address) # Handle "exceptional conditions" # Handle exceptions for s in exceptional: print ('exception condition on ', s. getpeername () # Stop listening for input on the connection inputs. remove (s) if s in outputs: outputs. remove (s) s. close () # Remove message queue del message_queues [s] sleep (1)

Client:

# Coding: utf-8import socketmessages = ['this is the message', 'it will be sent', 'in parts',] server_address = ('localhost', 8090) # Create aTCP/IP socketsocks = [socket. socket (socket. AF_INET, socket. SOCK_STREAM), socket. socket (socket. AF_INET, socket. SOCK_STREAM),] # Connect thesocket to the port where the server is listeningprint ('ing ing to % s port % s' % server_address) # Connect to the server for s in soc Ks: s. connect (server_address) for index, message in enumerate (messages): # Send messages on both sockets for s in socks: print ('% s: sending "% s" '% (s. getsockname (), message + str (index) s. send (bytes (message + str (index )). decode ('utf-8') # Read responses on both socketsfor s in socks: data = s. recv (1024) print ('% s: received "% s"' % (s. getsockname (), data) if data! = "": Print ('closingsocket ', s. getsockname () s. close ()

Two problems were encountered during code writing. First, how to determine whether the client has closed the socket connection, and then I analyzed it myself. If the client socket is disabled, then the data received by the server is ''. Add this judgment. Second, if the socket is disabled on the server, an error will be reported once the socket-related method is called, regardless of whether the socket is stored in different containers (that is, list_1 stores socket1, list_2 stores socket1 and I disabled socket1. Neither of them can call this socket)

Server:

Client:

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.