将多任务(多线程)引入到udp聊天机器人,可以实现同时发送消息和接收消息
1 import socket 2 import threading 3 4 5 def udp_send(udp_socket,ip,port): 6 while True: 7 try: 8 # 获取发送的信息 9 data = input(‘请输入要发送的信息:‘) 10 udp_socket.sendto(data.encode(‘gbk‘), (ip,port)) 11 12 except Exception as erro: 13 print(‘错误类型:‘,erro) 14 15 16 def udp_recv(udp_socket): 17 while True: 18 # 接收信息 19 recv_data = udp_socket.recvfrom(1024) 20 print(‘接收的信息:‘,recv_data[0].decode(‘gbk‘)) 21 22 23 def main(): 24 25 # 创建UDP套接字 26 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 27 28 # 绑定本地信息 29 udp_socket.bind((‘‘,8080)) 30 31 # 获取对方通信地址 32 ip = input(‘请输入对方的ip:‘) 33 port = int(input(‘请输入对方的端口port:‘)) 34 35 # 创建线程 36 t1 = threading.Thread(target=udp_send, args=(udp_socket, ip, port)) 37 t2 = threading.Thread(target=udp_recv, args=(udp_socket,)) 38 t1.start() 39 t2.start() 40 41 42 if __name__ == ‘__main__‘: 43 main()
原文地址:https://www.cnblogs.com/summer1019/p/10430218.html
时间: 2024-11-09 01:59:30