Reference text
Liaoche Python Tutorials
TCP is to establish a reliable connection, and both sides of the communication can send data in the form of a stream. The relative tcp,udp is a non-connection oriented protocol.
when using the UDP protocol, you do not need to establish a connection, just need to know the other side's IP address and port number , you can directly send packets. But I don't know if I can get there. Although it is unreliable to transmit data with UDP, it
has the advantage of being faster than TCP, and can use UDP protocol for data that does not require reliable arrival.
Service-side code
#Importing the socket libraryImportSocket#Create a IPV4,UDP sockets =Socket.socket (socket.af_inet, socket. SOCK_DGRAM)#bound Port:S.bind (('127.0.0.1', 9999))#no need to open listen, directly receive all the dataPrint('Bind UDP on 9999') whileTrue:#receive data from the client, using Recvfromdata, addr = S.recvfrom (1024) Print('Received from%s:%s.'%addr) s.sendto (b'Hello,%s!.'% data, addr)
Client code
ImportSockets=Socket.socket (socket.af_inet, socket. SOCK_DGRAM)#you do not need to establish a connection: forDatainch[b'Michael'B'ALice'B'FF']: #send data to client:S.sendto (Data, ('127.0.0.1', 9999)) #receive data from the client: Print(S.recvfrom (1024x768) [0].decode ('Utf-8') ) S.close ()
Demo effect
Python's UDP programming