views:

39

answers:

3

I'm having trouble closing my socket when exiting my Java application. I thought that an easy way to make sure the socket gets closed is to hook it on windowClosing in a Swing JFrame like this:

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            input.close();
            output.close();
            socket.close();

            frame.dispose();
            System.exit(0);
        }
    });

But then I have to handle the IOException that close() creates, and I can't throw it when overriding the event method like that.

How can I make sure that my streams and my socket get closed when the program does?

Thanks.

+1  A: 

You don't need to throw it. Just catch it.

try {
  if(null != input) {
    input.close();
  }
} catch(IOException ex) {
  // Log or ignore the exception.
}

Also, you don't need to call the dispose() or System.exit(0); methods if your main application Frame is already closing.

Make sure that the following is set on your main Application JFrame.

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
S73417H
When I catch the exception like that, the window doesn't close. It just sits and I have to kill the run from the IDE. Also, the socket still doesn't close. Not sure how I can make this work.
FrogOfDoom
You must set the following on your main Application Frame.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
S73417H
I've got that on already. Thanks, though.
FrogOfDoom
A: 

Make sure that you don't block the event dispatch thread -- the close() methods might block in some cases.

seand
How would I tell if it blocks? And if it does, how can I prevent it?Thanks.
FrogOfDoom
It may depend on the environment. For example on the blackberry close() methods may block for 2 minutes. So (as bad as it sounds) the fix was to spawn a thread just to close the sockets!
seand
A: 

Solved this problem by catching the IOException, as S73417H said, and making sure to close the streams in this order: output, input, socket. Thanks to everyone who answered.

FrogOfDoom
Keep in mind closing the Socket closes the input and output streams on its own, you're doing extra work.
Ryan
@FrogOfDoom, StackOverflow is not a forum. You should delete this post and instead accept the answer you found most helpful.
Tim Bender