Introduction: at the same time, both ends of the chat device and can send and receive data
. 1 Import Socket 2 Import Threading . 3 . 4 UDP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) . 5 . 6 . 7 DEF send_msg (DEST_IP, dest_port): . 8 "" " transmission data " "" . 9 the while True: 10 the send_data = INPUT ( " Please enter your data to be transmitted: " ) . 11 udp_socket.sendto (send_data.encode ( ' GBK ' ), (DEST_IP, dest_port)) 12 is 13 is 14 DEF recv_msg (): 15 "" "接收数据""" 16 while True: 17 recv_data = udp_socket.recvfrom(1024) 18 print("%s:%s" % (recv_data[1], recv_data[0].decode('gbk'))) 19 # print(recv_data) 20 21 22 def main(): 23 # udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 24 udp_socket.bind(('', 7788)) 25 dest_ip = input("请输入对方的IP:") 26 dest_port = int (INPUT ( " Please enter the other's Port: " )) 27 # # send data 28 # send_msg (IP, Port) 29 # 30 # # received data 31 is # recv_msg () 32 33 is # multi-task separately performs transmission and receiving data 34 is t_recv of the threading.Thread = (target = recv_msg) 35 t_send of the threading.Thread = (target = send_msg, args = (DEST_IP, dest_port)) 36 t_recv.start () 37 [ t_send.start () 38 is 39 40 IF the __name__ = = ' __main__': 41 main()