【python版本】3.6
UDP服务器端:
1 from socket import * 2 from time import ctime 3 4 host = '' 5 port = 21567 6 buf_size = 1024 7 addr = (host, port) 8 9 udpSerSock = socket(AF_INET, SOCK_DGRAM) 10 udpSerSock.bind(addr) 11 12 while True: 13 print("waiting for message...") 14 data, ADDR = udpSerSock.recvfrom(buf_size) 15 response = '[%s] %s' % (ctime(), data.decode('utf-8')) 16 udpSerSock.sendto(response.encode('utf-8'), ADDR) 17 print("...received from and returned to:", ADDR) 18 19 udpSerSock.close()
UDP客户端:
1 from socket import * 2 3 4 host = 'localhost' 5 port = 21567 6 buf_size = 1024 7 addr = (host, port) 8 9 10 udpCliSock = socket(AF_INET, SOCK_DGRAM) 11 12 while True: 13 data = input('>') 14 if not data: 15 break 16 udpCliSock.sendto(data.encode('utf-8'), addr) 17 data, addr = udpCliSock.recvfrom(buf_size) 18 if not data: 19 break 20 print(data.decode('utf-8')) 21 22 udpCliSock.close()