import socket def send_msg(udp_socket): """发送消息""" # 获取要发送的内容 desk_ip = input("输入对方的ip:") desk_port = int(input("输入对方的port:")) send_date = str(input("请输入要发送的消息:")) udp_socket.sendto(send_date.encode("utf-8"), (desk_ip, desk_port)) def recv_msg(udp_socket): # 接受并显示 recv_date = udp_socket.recvfrom(1024) print("%s:%s" % (str(recv_date[1]), recv_date[0].decode("utf-8"))) def main(): # 创建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定信息 udp_socket.bind(("", 8080)) # 循环来处理事情 while True: print("*" * 50) print("1:发送消息") print("2:接收消息") print("0:退出系统") op = input("请输入功能:") if op == "1": # 发送 send_msg(udp_socket) elif op == "2": # 接受并显示 recv_msg(udp_socket) elif op == "0": break else: print("输入错误重新输入") if __name__ == '__main__': main()