服务端:
1 import socket 2 3 ip_port = ('127.0.0.1', 9000) 4 BUFSIZE = 1024 5 udp_server_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 6 7 udp_server_client.bind(ip_port) 8 9 while True: 10 msg, addr = udp_server_client.recvfrom(BUFSIZE) 11 print("recv", msg, addr) 12 13 udp_server_client.sendto(msg.upper(), addr)
客户端“
1 import socket 2 3 ip_port = ('127.0.0.1', 9000) 4 BUFSIZE = 1024 5 udp_server_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 6 7 while True: 8 msg = input('>>:').strip() 9 if not msg: 10 continue 11 udp_server_client.sendto(msg.encode('utf-8'), ip_port) 12 13 back_msg, addr = udp_server_client.recvfrom(BUFSIZE) 14 print(back_msg.decode('utf-8'), addr)
先启动服务端,再启动客户端,在客户端输入信息,
客户端运行结果为:
1 >>:媳妇 2 媳妇 ('127.0.0.1', 9000) 3 >>:abc 4 ABC ('127.0.0.1', 9000) 5 >>:sdfghjkl;wertyuio 6 SDFGHJKL;WERTYUIO ('127.0.0.1', 9000) 7 >>:
服务端运行结果为:
1 recv b'xe5xaaxb3xe5xa6x87' ('127.0.0.1', 60861) 2 recv b'abc' ('127.0.0.1', 60861) 3 recv b'sdfghjkl;wertyuio' ('127.0.0.1', 60861)