@ (Network programming)
What is 1.UDP?
Internet Protocol Set supports a connectionless transport protocol, which is called User Datagram Protocol (UDP). UDP provides a way for applications to send encapsulated IP datagrams without establishing connections. RFC 768  describes UDP.
The transport layer of the Internet has two main protocols that complement each other. Connectionless is UDP, which does not do anything special except to send data packets to applications and allow them to structure their own protocols at the required level. Connection-oriented is TCP, which does almost everything.
2. Code Implementation
import socket def main(): #Create a udp socket udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #If there are no bindings, the receiver has only random ports to receive udp_socket.bind(("",7789)) while True: #get data send_data = input("Please enter the data to be sent") if send_data == "exit": break #ip,port address = ("127.0.0.1",7788) #The first parameter to send and receive data using sockets must be binary data. The second parameter is a tuple (ip,port). # udp_socket.sendto(b"hahaha",address) udp_socket.sendto(send_data.encode("utf-8"),address) #Close udp_socket.close() if __name__ == '__main__': #Sender Server Start main()
import socket def main(): # Create a udp socket udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind local information. If a network program is not bound, the system will be allocated randomly. address = ("127.0.0.1", 7788) udp_socket.bind(address) for i in range(0,100): #The data 1024 waiting to be sent by the receiving party represents the maximum number of bytes received at a time. recv_data = udp_socket.recvfrom(1024) recv_mess = recv_data send_addre = recv_data print(recv_mess.decode("utf-8"),str(send_addre))#recv_mess.decode("utf-8") # Close udp_socket.close() if __name__ == '__main__': print("Receiving Server Start") main()
- Receiver must bind port and ip address
- The sender can be unbound, at which point the host allocates a random port
- The data sent from the sending end must be encoded, and the corresponding receiver must decode it.
- recvfrom is followed by the number of bytes
- The data returned by recvfrom is a list of waving tuples, of which 0 is the received data and 1 is the sender's address.