我正在用 Java 编写一个类来简化连接、加入、发送和接收来自多播组的数据的过程。在这一点上,我遇到了receive()
JavaMulticastSocket
类中的方法的问题。每当我使用这种方法时,整个程序都会暂停,直到收到数据。
我想知道是否有一种方法可以让它只听给定的持续时间,比如 5 秒?
这是我正在做的一个非常基本的代码示例。请注意,它根本不像我的实际代码,除了异常捕获、导入语句等......它只是展示了我的类的基本流程,它如何利用 Java 的多播能力:
//Connect to the multicast host, and join the group
MulticastSocket msConn = new MulticastSocket(5540);
InetAddress netAddr = InetAddress.getByName("239.255.255.255");
msConn.joinGroup(netAddr);
//Preapre a datagram packet in which to place recieved data
byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
//PROBLEM: Code halts here until data is recieved
//Accoding the the Java Docs it says that
//"This method blocks until a datagram is received."
msConn.recieve(pack);
感谢您的时间。