0

I'm creating a MulticastSocket at a certain port and then joining a group. Now the socket keeps receiving datapackets as long as they are broadcasted. So I call the socket.receive in a while loop which is always true. Now I never leave the group. But If i terminate my program, does it close the socket automatically? I need some clarification on this.

Also, If I definitely need to leave said group and close the socket, how can I achieve that?. I have tried using addShutdownHook

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                public void run() {
                    System.out.println("Closing Broadcast Port");
                    multi.shutsocket();
                }
            }, "Shutdown-thread"));

But it's not working for some odd reason.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • The operating system will close it, but you should also make a practice of releasing your own resources. – user207421 Jul 20 '16 at 09:00
  • @EJP I know I should, and that's what the second part of my question was. Because my while loop is always running. If I close the socket after the loop, it would be unreachable. However, I've been trying to leave the multicast group and close the socket "on termination". However, using `addShutdownHook` isn't helping. Any other alternatives? – Piyush Shandilya Jul 20 '16 at 09:16
  • The shutdown hook should be a runnable, not a thread. – user207421 Jul 20 '16 at 21:32
  • @EJP addShutdownHook takes in Thread as argument. – Piyush Shandilya Jul 21 '16 at 06:15

0 Answers0