server.py
# socket编程-udp from socket import * import time ip_port = ('127.0.0.1', 8080) buffer_size = 1024 udp_server = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM代表数据报式套接字,即udp udp_server.bind(ip_port) while True: # 不需要listen及accept建立连接,直接进入通讯循环 data, addr = udp_server.recvfrom(buffer_size) data = (data.decode('utf-8')) print(data) back_time = time.strftime('%Y-%m-%d %X') newstr = '%s %s' % (back_time, data) udp_server.sendto(newstr.encode('utf-8'), addr) udp_server.close()
client.py
from socket import * ip_port = ('127.0.0.1', 8080) buffer_size = 1024 udp_client = socket(AF_INET, SOCK_DGRAM) while True: msg = input('===>').strip() udp_client.sendto(msg.encode('utf-8'), ip_port) data, addr = udp_client.recvfrom(buffer_size) print(data.decode('utf-8')) udp_client.close()