Select Simple example, with comments

Source: Internet
Author: User

All in the code:

Import selectimport socketimport Queue "" "Simple select realizes Echo Server Personal understanding: Select Programming Idea, let select Go to judge can read or can write. If you can read or write, select will tell readable or writeable, then you have to let the file handle to read or write, here is Scoket,recv () or scoket.send () to perform the actual operation "" "Server = Socket.socket () # Gets a socket server.setblocking (False) # set to non-blocking mode Server.bind ((' 127.0.0.1 ', 9001)) # bind IP and Port server.listen ( 5) # Start monitoring, to this step can see the listening status in Netstat, if there is no server.accept (), the client connection will be rejected inputs = [Server] # Set the input queue, when the server's listener receives the guest When the user connects, select considers the server to be readable, so that server.accpet () is allowed to receive the client connection # or when the socket has new data sent, select considers the socket to be readable. , you have to let the socket recv () to receive data outputs = [] # When the socket can send data to the peer, select will determine that the socket is message_queue = {} # Message Queuing , the key value for socket socket n = 0 # reflects the number of while loops while inputs: # Inputs releases the Presence value print ("Waiting for C Onnect ...,%s "%n) readable, writeable, exceptions = Select.select (inputs,outputs,inputs) # Select is like a very powerful    Monitor to monitor whether individual file handles are readable and writable. For s in readable: # loop readableOf          If S is server: # If it is a Select socket print ("Server can read ...") conn, addr = S.accept () # on receiving Client connection print ("Welcome (%s,%s) to connect ..."%addr) inputs.append (conn) #            Inputs, instead of receiving or taking data immediately, is placed in the socket. # s.setblocking (False) Else: # If it is not a server socket Try:data = s.re CV (1024) # indicates that the client connection socket received the data sent by the client except Exception as E: # The client process was forced to shut down, causing the client to send the RST package.                Connectionreseterror print (e) inputs.remove (s) # If the client exits, say that the socket is removed from the inputs                                          If s in outputs: # If the socket exists in outputs, the socket is removed from the outputs because the client is closed                    # also put the socket in the outputs, no, no data. Outputs.remove (s) s.close () # Remember to close this socket break # here to break            , because S.RECV (1024) is abnormal, data is not defined at all, and the following if data will error. If Data: # If there is print ("recv from%s:%s"% (S.getpeername (), Data.decode ())) Message_queue[s] = queue.                     Queue () # put incoming data into message queue Message_queue[s].put (data) outputs.append (s)            # because it is echo server, all the Youdao data will have to return the original data, but here does not return immediately, but to select.                Else:print ("The Client (%s,%s) is closed"%s.getpeername ()) # If data is empty, it means that the client gracefully shuts down the connection and the client sends Fin. If s in outputs: # The client shuts down, and the socket doesn't have to be placed in outputs and inputs Outputs.remo ve (s) inputs.remove (s) del Message_queue[s] # Message Queuing can also be cleared s.cl OSE () # Close socket for s in writeable: # If writable, "as if the ouputs has a connected socket exists is writable. "Try:data = message_queue[s].get_nowait () # Gets the message to be sent except queue.            Empty: # Message Queuing is also writable. Print ("outpt Queue for (%s,%s) in Empty "%s.getpeername ()) Outputs.remove (s) # because it is the echo server, Message Queuing            is empty, the description has responded to the data to the end, it is not necessary to always determine whether the socket is writable.            # s.close () # No data to send does not mean to close the socket Else:print ("Send data to Client (%s,%s)"%s.getpeername ()) S.send (data) Outputs.remove (s) # After sending the data, you can actually remove the socket from the outputs because it is the echo server for s in except                Ions: # If error occurs print ("Expect happend on (%s,%s)"%s.getpeername ()) Inputs.remove (s)                       # Remove the socket from the inouts,outputs if s in Outputs:outputs.remove (s) s.close () # connection to close del Message_queue[s] # Message Queuing also to turn off n + = 1 # See how many times the while loop can
1 """2 Operation Result:3 Waiting for Connect ..., 04 server can read ...5 Welcome (127.0.0.1,56348) to connect ...6 Waiting for Connect ..., 17 recv from (' 127.0.0.1 ', 56348): the 1st client8 Waiting for Connect ..., 29 Send data to Client (127.0.0.1,56348)Ten Waiting for Connect ..., 3 One server can read ... A Welcome (127.0.0.1,56349) to connect ... - Waiting for Connect ..., 4 - recv from (' 127.0.0.1 ', 56349): The 2th client the Waiting for Connect ..., 5 - Send data to Client (127.0.0.1,56349) - Waiting for Connect ..., 6 - recv from (' 127.0.0.1 ', 56349):2th would kill by OS  + Waiting for Connect ..., 7 - Send data to Client (127.0.0.1,56349) + Waiting for Connect ..., 8 A [Winerror 10054] The remote host forced the shutdown of an existing connection.  at Waiting for Connect ..., 9 - recv from (' 127.0.0.1 ', 56348):1st would s.close () close the socket  - Waiting for connect ..., - Send data to Client (127.0.0.1,56348) - Waiting for Connect ... - The client (127.0.0.1,56348) is closed  in Waiting for connect ..., - """

  

Client:

Import sockets = Socket.socket () s.connect ((' 127.0.0.1 ', 9001)) while True:    data = input (">>"). Strip ()    if data = = "":        continue    if data = = "Q":        S.close () Break    s.send (bytes (data,encoding= "Utf-8"))    data = S.RECV (1024x768)    print ("recv:", Data.decode ())

  

Select Simple example, with comments

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.