William
William

Reputation: 20196

How to rejoin a multicast group in Java

I have a scenario in which the router may be down when my multicast listener joins the group. In that scenario then multicast messages will never reach the listener.

So I plan on letting the listener timeout and then rejoin the multicast group.

The problem is that the following code does not ensure that the listener successfully registers and receives the multicast messages.

  final MulticastSocket mcSocket = new MulticastSocket(POR); 

  // Join group before router started
  mcSocket.joingGroup(mcAddress);

  // wait until router starts
  Thread.sleep(LONG_TIME);

  mcSocket.leaveGroup(mcAddress);

  // Join group after router started.
  // Expected that this would re-register listener with router, but it doesn't
  mcSocket.joingGroup(mcAddress);

  // packet is never received
  mcSocket.receive(packet);

So, what do I need to do to ensure that the listener re-registers with the router?

Upvotes: 1

Views: 741

Answers (1)

user207421
user207421

Reputation: 310860

I would try a different strategy. I would set a longish read timeout, with setSoTimeout(), and if it expires I would then leave the group, sleep for a bit, then rejoin. That way it will happen every time, not just at startup. You probably need to sniff the network to make sure that IGMP JOIN messages are actually going out when you do the re-join.

Upvotes: 1

Related Questions