1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import socket import threading
class chatudp: def __init__(self,dest_ip,dest_port): self.dest_ip = dest_ip self.dest_port = dest_port self.udp_socket =socket.socket(socket.AF_INET,socket.SOCK_DGRAM) self.udp_socket.bind(("",8881)) def recvmsg(self): while True: recv_data=self.udp_socket.recvfrom(1024) print(recv_data[0].decode('gb2312')) def sendmsg(self,dest_ip, dest_port): while True: sent_msg = input("输入要发送的数据:") self.udp_socket.sendto(sent_msg.encode("utf8"), (dest_ip, dest_port)) def run(self): thread_recv=threading.Thread(target=self.recvmsg) thread_send=threading.Thread(target=self.sendmsg,args=(self.dest_ip,self.dest_port)) thread_recv.start() thread_send.start() def main(): dest_ip="10.101.0.104" dest_port=8088 msg=chatudp(dest_ip,dest_port) msg.run() if __name__ == '__main__': main()
|