Python network Programming (ix)

Source: Internet
Author: User
Tags set socket

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)

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.