python-for IO multiplexing based on socket and select modules

Source: Internet
Author: User
Tags epoll

"IO refers to the input and output, part refers to the file operation, and part
Network transport operations, such as SOEKCT, are one of them; multiplexing refers to the
Use a mechanism that uses multiple IO simultaneously, such as listening to multiple file sentences simultaneously
Handle (once the socket object transmits or receives information), once the file handle is
Now, the change will immediately perceive
‘‘‘
1. Enable multi-person simultaneous connection to the socket server via IO multiplexing
ImportSocket SK1= Socket.socket ()#SK1,SK2,SK3 This is a file descriptorSk1.bind (('127.0.0.1', 8002) ) Sk1.listen () Sk2=socket.socket () Sk2.bind ('127.0.0.1', 8003) ) Sk2.listen () Sk3=socket.socket () Sk3.bind ('127.0.0.1', 8004) ) Sk3.listen () inputs=[SK1,SK2,SK3]ImportSelect whileTrue:" "[Sk1,sk2,sk3],select automatically listens for Sk1,sk21,sk3 three objects once a handle changes, it will be heard ." "    #If someone links sk1, it will be added to the list, r_list = [Sk1]R_list,w_list,e_list = Select.select (inputs,[],[],1)#1 means wait a second, monitor one second while execution is here, and then loop when no one is linked .    #print (R_list,sk1.listen ())     forSkinchr_list:conn,address=sk.accept ()#print (conn,address)Conn.sendall (Bytes ('Hello', encoding='Utf-8') ) Conn.close ()
#Client OneImportSocket obj=socket.socket () Obj.connect ('127.0.0.1', 8002) ) Content= str (OBJ.RECV (1024x768), encoding='Utf-8')Print(content) Obj.close ()#Client TwoImportSocket obj=socket.socket () Obj.connect ('127.0.0.1', 8003) ) Content= str (OBJ.RECV (1024x768), encoding='Utf-8')Print(content) Obj.close ()#Client ThreeImportSocket obj=socket.socket () Obj.connect ('127.0.0.1', 8004) ) Content= str (OBJ.RECV (1024x768), encoding='Utf-8')Print(content) Obj.close ()

Execution result: As long as the server side is started, then different clients can receive the message multiple times, multiple ports are successfully monitored

2. Use the Select module below for multiplexing, so that the same port receives multiple links at the same time

ImportSocket SK1= Socket.socket ()#SK1,SK2,SK3 This is a file descriptorSk1.bind (('127.0.0.1', 8002) ) Sk1.listen ()##sk2 = Socket.socket ()#Sk2.bind ((' 127.0.0.1 ', 8003))#Sk2.listen ()##SK3 = Socket.socket ()#Sk3.bind ((' 127.0.0.1 ', 8004))#Sk3.listen ()Inputs=[Sk1]ImportSelect#Epoll is more efficient, but Windows does not support it, it is the person who has the problem to tell it, do not follow the bad whileTrue:" "[Sk1,sk2,sk3],select automatically listens for Sk1,sk21,sk3 three objects once a handle has changed (someone is linked) it will be heard" "    #If someone links sk1, it will be added to the list, r_list = [Sk1]R_list,w_list,e_list = Select.select (inputs,[],[],1)    " "The third parameter is the listener error, as long as there is an error, it will be monitored, return e_list the second parameter returned to W_list, as long as the transmission of what, the intact passed to W_list" "    Print('listening on%s number of objects'%len (inputs)) forSkinchr_list:ifSK = =Sk1:#The handle is the same as the server-side object, indicating that a new user is linked to theConn,address =sk.accept () inputs.append (conn)#after joining, inputs has a linked object and a server object        Else:            #There's a message from an old user.            Try: Data_byte=SK.RECV (1024) Data_str=str (data_byte,encoding='Utf-8') Sk.sendall (bytes (data_str+'Roger that.', encoding='Utf-8'))            except:#The null message indicates that the client has broken the link, so it is removed from the listenerInputs.remove (SK)#The SK here is the Conn that was passed in, because R_list received a variable value .                

Once this server is started, it can be multiplexed and can receive multiple clients connecting at the same time.

3. Here are some of the multi-channel operations inside the read/write separation

ImportSocket SK1= Socket.socket ()#Sk1 is a file descriptorSk1.bind (('127.0.0.1', 8002) ) Sk1.listen () inputs= [Sk1]#the handle of the detected change is placed hereOutputs=[]#used to record who sent the message to the server in order to replyMessage_dict = {}#To receive information, a key-value pair is formed according to the handleImportSelect#Epoll is more efficient, but Windows does not support it, it is the person who has the problem to tell it, do not follow the bad whileTrue:" "[Sk1,sk2,sk3],select automatically listens for Sk1,sk21,sk3 three objects once a handle has changed (someone is linked) it will be heard" "    #If someone links sk1, it will be added to the list, r_list = [Sk1]R_list,w_list,e_list = Select.select (inputs,outputs,inputs,1)    " "The third parameter is the listener error, as long as there is an error, it will be monitored, return e_list the second parameter returned to W_list, as long as the transmission of what, the intact passed to W_list" "    Print('listening on%s number of objects'%len (inputs)) forSkinchr_list:ifSK = =Sk1:#The handle is the same as the server-side object, indicating that a new user is linked to theConn,address =sk.accept () inputs.append (conn)#after joining, inputs has a linked object and a server objectMessage_dict[conn]=[]#The key of the dictionary is the specific linked object        Else:            #There's a message from an old user.            Try: Data_byte=SK.RECV (1024)             exceptException as E:#The null message indicates that the client has broken the link, so it is removed from the listener                Print(e) inputs.remove (SK)#The SK here is the Conn that was passed in, because R_list received a variable value .            Else: Data_str= str (data_byte, encoding='Utf-8') message_dict[sk].append (DATA_STR) outputs.append (SK)#add a handle to the transmitted data to the second argument     forConninchW_list:recv_str=MESSAGE_DICT[CONN][0]#Get the information we received.        delMESSAGE_DICT[CONN][0]#Delete Information to prevent the next occurrence of the same message        Print(recv_str) conn.sendall (bytes (recv_str+'Roger that.', encoding='Utf-8')) Outputs.remove (conn)#Delete in list after reply is completed     forSk_or_conninchE_list:e_list.remove (sk_or_conn)

This can create a simple read-write separation operation

python-for IO multiplexing based on socket and select modules

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.