1

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.

neapsix
  • 11
  • 2

3 Answers3

2

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
  • 2,661
  • 3
  • 23
  • 37
  • 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. – neapsix Jul 23 '10 at 02:37
  • You must set the following on your main Application Frame. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); – S73417H Jul 23 '10 at 02:59
0

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

seand
  • 5,168
  • 1
  • 24
  • 37
  • How would I tell if it blocks? And if it does, how can I prevent it? Thanks. – neapsix Jul 23 '10 at 03:00
  • 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 Jul 23 '10 at 03:24
0

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.

neapsix
  • 11
  • 2
  • 1
    Keep in mind closing the Socket closes the input and output streams on its own, you're doing extra work. – Ryan Jul 23 '10 at 03:41
  • StackOverflow is not a forum. You should delete this post and instead accept the answer you found most helpful. – Tim Bender Jul 23 '10 at 06:00