Server:
1 from socket import * 2 3 server = socket(AF_INET, SOCK_DGRAM) 4 server.bind(('127.0.0.1', 8080)) 5 6 while True: 7 data, client_addr = server.recvfrom(1024) 8 print(data, client_addr) 9 10 server.sendto(data.upper(), client_addr) 11 12 server.close()
Client:
1 from socket import * 2 3 client = socket(AF_INET, SOCK_DGRAM) 4 5 while True: 6 msg = input(">>:").strip() 7 client.sendto(msg.encode('utf-8'), ('127.0.0.1', 8080)) 8 9 data, server_addr = client.recvfrom(1024) 10 print(data, server_addr) 11 12 client.close()
Start the server first, then start the client, enter the lowercase letters abc on the client,
The client running result is:
1 >>:abc 2 b'ABC' ('127.0.0.1', 8080) 3 >>:
The result of running the server is:
1 b'abc' ('127.0.0.1', 55255)
This implements a simple socket program based on the udp protocol
Sockets based on the udp protocol can send nulls:
Enter empty on the client side,
The client running result is:
1 >>: 2 b'' ('127.0.0.1', 8080) 3 >>: 4 b'' ('127.0.0.1', 8080) 5 >>:
Even if the data sent by udp is empty, udp is a datagram protocol, and the datagram also contains ip port information, so the datagram is not empty.