效果展示
网络调试助手下载链接:https://pan.baidu.com/s/1f9wTqRhAeyUN87XDcQUa7w提取码: kgur
1 import socket 2 3 4 def send_msg(udp_socket, send_data): 5 """发送数据""" 6 send_data = send_data 7 udp_socket.sendto(send_data.encode('gbk'), ('192.168.2.101', 8080)) 8 9 10 def recv_msg(udp_socket): 11 """接收收据""" 12 recv_data = udp_socket.recvfrom(1024) 13 send_adress = recv_data[1] 14 send_content = recv_data[0].decode('gbk') 15 print('%s:%s' %(send_adress, send_content)) 16 17 18 def main(): 19 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 20 udp_socket.bind(('', 7788)) 21 # 循环收发数据 22 while True: 23 print("___UDP聊天器___") 24 print("1.发送数据") 25 print("2.接收数据") 26 print("3.退出聊天") 27 op = input("请输入功能:") 28 if op == "1": 29 send_data = input("请输入要发送的数据:") 30 send_msg(udp_socket, send_data) 31 elif op == "2": 32 recv_msg(udp_socket) 33 elif op == "3": 34 break 35 else: 36 print("您的输入有误,请重新输入") 37 38 39 if __name__ == '__main__': 40 main()