I am writing a class in Java to simplify the process of connecting to, joining, sending, and receiving data from a multicast group. At this point, I am having trouble with the receive()
method in Java's MulticastSocket
class. Whenever I use this method, the entire program halts until data is received.
I would like to know if there is a way that I can have it listen for only a given duration, say, 5 seconds?
Here is a very basic code sample of what I am doing. Note that it does not at all resemble my actual code, with the exception catching, import statements, etc... it simply shows the basic flow of my class in how it leverages Java's multicasting abilities:
//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);
Thank you for your time.