服务端:
#UDP from socket import * ip_port=('127.0.0.1',8000) buffer_size=1024 udp_server=socket(AF_INET,SOCK_DGRAM)#数据报 udp_server.bind(ip_port) while True: data,addr=udp_server.recvfrom(buffer_size)#recvfrom收的是元祖内容形式, print(data) udp_server.sendto(data.upper(),addr)
客户端:
#UDP from socket import * ip_port=('127.0.0.1',8000) buffer_size=1024 udp_client=socket(AF_INET,SOCK_DGRAM)#数据报 while True: msg=input('>>').strip() # udp_client.sendto('hello,baby'.encode('utf-8'),ip_port)#客户端把hello发到IP加端口 #udp必须加上发送的端口和地址 udp_client.sendto(msg.encode('utf-8'), ip_port) data,addr=udp_client.recvfrom(buffer_size) print(data.decode('utf-8'))