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