[Reprint]python Socket Programming Example

Source: Internet
Author: User

UDP communication.

Server:

ImportSocketport=8081s=Socket.socket (Socket.af_inet,socket. SOCK_DGRAM)#From the specified port, from any sender, to receive UDP dataS.bind (("', port))Print('waiting for access ...') whileTrue:#receive a dataData,addr=s.recvfrom (1024)    Print'Received:', data,' from', addr

Client:

Import socketport=8081Host='localhost's=Socket.socket ( Socket.af_inet,socket. SOCK_DGRAM) s.sendto (b'hello,this is a test info! ) ', (Host,port))

When you run the program, start two terminals, and then run a program on each terminal.

TCP mode.

Server:

#-*-coding:utf-8-*- fromSocketImport* fromTimeImportCTime fromTimeImportlocaltimeImportTimehost="'PORT=1122#Setting the Listening portbufsiz=1024ADDR=(HOST, PORT) sock=socket (af_inet, Sock_stream) sock.bind (ADDR) Sock.listen (5)#Set Exit Criteriastop_chat=False while  notStop_chat:Print('waiting for access, listening port:%d'%(PORT)) Tcpclientsock, addr=sock.accept ()Print('Accept connection, client address:', addr) whileTrue:Try: Data=tcpclientsock.recv (Bufsiz)except:            #print (e)tcpclientsock.close () Break        if  notData: Break        #python3 Use bytes, so encode        #the message sent to me by s= '%s is: [%s]%s '% (Addr[0],ctime (), Data.decode (' UTF8 '))        #Format the dateisotimeformat='%y-%m-%d%x'stime=time.strftime (Isotimeformat, LocalTime ()) s='the message sent to me by%s is:%s'% (Addr[0],data.decode ('UTF8')) Tcpclientsock.send (S.encode ('UTF8'))        Print([Stime],':', Data.decode ('UTF8'))        #If you enter quit (ignoring case), the program exitsStop_chat= (Data.decode ('UTF8'). Upper () = ="QUIT")        ifStop_chat: Breaktcpclientsock.close () sock.close ( )

Client:

#-*-coding:utf-8-*- fromSocketImport*classTcpClient:#testing, connecting the machinehost='127.0.0.1'    #Setting the Listening portport=1122Bufsiz=1024ADDR=(HOST, PORT)def __init__(self): self.client=socket (af_inet, sock_stream) self.client.connect (self. ADDR) whileTrue:data=input ('>')            if  notData: Break            #The Python3 Pass is bytes, so encodeSelf.client.send (Data.encode ('UTF8'))            Print('send information to%s:%s'%(self.) Host,data))ifData.upper () = ="QUIT":                 BreakData=Self.client.recv (self. Bufsiz)if  notData: Break            Print('message received from%s:%s'% (self. Host,data.decode ('UTF8')))                        if __name__=='__main__': Client=tcpclient ()

[Reprint]python Socket Programming Example

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.