多线程UDP聊天
简介:同一时间,聊天器两端均可收发数据
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 """发送数据""" 9 while True: 10 send_data = input("请输入您要发送的数据:") 11 udp_socket.sendto(send_data.encode('gbk'), (dest_ip, dest_port)) 12 13 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("请输入对方的Port:")) 27 # # 发送数据 28 # send_msg(ip, port) 29 # 30 # # 接收数据 31 # recv_msg() 32 33 # 多任务分别执行发送和接收数据 34 t_recv = threading.Thread(target=recv_msg) 35 t_send = threading.Thread(target=send_msg, args=(dest_ip, dest_port)) 36 t_recv.start() 37 t_send.start() 38 39 40 if __name__ == '__main__': 41 main()