1 # -*- coding:utf-8 -*- 2 # Author:Sure Feng 3 import socket 4 5 6 def send_msg(udp_socket): 7 """获取键盘数据,并将其发送给对方""" 8 # 获取对方ip、端口 9 dest_ip = input("请输入对方的ip") 10 dest_port = input("请输入对方的端口") 11 # 获取要发送的信息 12 msg = input("请输入要发送的信息") 13 # 按照utf8编码后,发送数据 14 udp_socket.sendto(msg.encode("utf-8"), (dest_ip, int(dest_port))) 15 16 17 def rece_msg(udp_socket): 18 # 接收数据 19 msg = udp_socket.recvfrom(1024) 20 # 解码 21 recv_ip = msg[1] 22 recv_msg = msg[0].decode("utf-8") 23 # 显示解码后数据 24 print("%s:%s" % (str(recv_ip), recv_msg)) 25 26 27 def main(): 28 # 创建套接字 29 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 30 # 绑定本地信息 31 udp_socket.bind(("", 9890)) 32 while True: 33 print("=" * 30) 34 print("1:发送消息") 35 print("2:接收消息") 36 print("=" * 30) 37 op_num = input("请输入要操作的功能序号:") 38 39 # 根据需求调用相应的函数 40 if op_num == "1": 41 send_msg(udp_socket) 42 elif op_num == "2": 43 rece_msg(udp_socket) 44 else: 45 print(">>> 输入有误,请重新选择") 46 47 48 # 关闭套接字 49 udp_socket.close() 50 51 52 if __name__ == "__main__": 53 print("main") 54 main()