socket_server_udp.py
import socket
# 创建UDP实例
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 定义绑定的ip和端口
ip_port = ("127.0.0.1", 8888)
# 绑定监听
sk.bind(ip_port)
# 不断循环接受数据
while True:
# 接收数据
data = sk.recv(1024)
# 打印数据
print(data.decode())
pass
socket_client_udp.py
import socket
# 定义实例
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 定义ip和port
ip_port = ("127.0.0.1", 8888)
# 循环数据的输入
while True:
# 输入发送的信息
msg_input = input("请输入发送的消息:")
# 退出循环的条件
if msg_input == 'exit':
break
# 数据发送
sk.sendto(msg_input.encode(), ip_port)
pass
# 发送关闭信息
sk.close()