Single-Process server-non-clogging mode server
#Coding=utf-8 fromSocketImport*Import Time#The socket used to store all the new linksG_socketlist = []defMain (): Sersocket=socket (af_inet, Sock_stream) sersocket.setsockopt (Sol_socket, SO_REUSEADDR,1) Localaddr= ("', 7788) Sersocket.bind (LOCALADDR)#You can modify the values in listen to see different phenomena.Sersocket.listen (1000) #set socket to non-clogging #When set to non-clogging, if the accept does not happen to have client connect, then accept will #generates an exception, so a try is required to handle itsersocket.setblocking (False) whileTrue:#used to test #Time.sleep (0.5) Try: Newclientinfo=sersocket.accept ()exceptException as Result:Pass Else: Print("A new client arrives:%s"%str (newclientinfo)) newclientinfo[0].setblocking (False) g_socketlist.append (newclientinfo) #used to store client information that needs to be deletedNeeddelclientinfolist = [] forClientsocket,clientaddrinchg_socketlist:Try: RecvData= CLIENTSOCKET.RECV (1024) ifLen (RecvData) >0:Print('recv[%s]:%s'%(str (CLIENTADDR), recvdata))Else: Print('[%s] client is closed'%str (CLIENTADDR)) Clientsocket.close () G_needdelclientinfolist.append (clientsock ET,CLIENTADDR))exceptException as Result:Pass forNeeddelclientinfoinchNeedDelClientInfoList:g_socketList.remove (needdelclientinfo)if __name__=='__main__': Main ()
Client
#Coding=utf-8 fromSocketImport*ImportRandomImportTimeserverip= Raw_input ("Please enter the IP of the server:") Connnum= Raw_input ("Please enter the number of times you want to link the server (for example,):") G_socketlist= [] forIinchRange (int (connnum)): s=socket (af_inet, Sock_stream) s.connect (ServerIP,7788)) G_socketlist.append (s)Print(i) whileTrue: forSinchg_socketlist:s.send (str (random.randint (0),100))) #used for testing #time.sleep (1)
Python network Programming (ix)