Service side:
1 fromSocketImport*2 3Server =socket (af_inet, SOCK_DGRAM)4Server.bind (('127.0.0.1', 8080))5 6 whileTrue:7data, client_addr = Server.recvfrom (1024)8 Print(data, client_addr)9 Ten server.sendto (Data.upper (), client_addr) One AServer.close ()
Client:
1 fromSocketImport*2 3Client =socket (af_inet, SOCK_DGRAM)4 5 whileTrue:6msg = input (">>:"). Strip ()7Client.sendto (Msg.encode ('Utf-8'), ('127.0.0.1', 8080))8 9data, server_addr = Client.recvfrom (1024)Ten Print(data, SERVER_ADDR) One AClient.close ()
Start the server first, then start the client, enter the lowercase ABC in the client,
The client runs the result as:
1 >>: ABC2 b'abc' ('127.0.0.1' , 8080)3 >>:
The server run results are:
1 b'abc' ('127.0.0.1', 55255)
This implements a simple socket program based on the UDP protocol.
UDP protocol-based sockets can be empty:
When the client input is empty,
The client runs the result as:
1 >>:2 b' ('127.0.0.1', 8080)3 >>:4 b' ('127.0.0.1', 8080) 5 >>:
UDP even if the sending data is empty, but UDP is the datagram protocol, the datagram also contains IP port information, so that the datagram is not empty
python--Network Programming-----Socket based on UDP protocol