1

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195

1 Answers1

3

Use the setSoTimeout() method to set a timeout for receiving a datagram. Then, as per the documentation for recieve(), it will throw a SocketTimeoutException if your timeout has elapsed, allowing you to continue with your program.

Mac
  • 14,615
  • 9
  • 62
  • 80