Hi there!
I'm trying to make a little chat server using Swing and NIO. I've got the main class based on JFrame, and a ServerBase object (based on the code from
http://java.about.com/gi/dynamic/offsite.htm?zi=1/XJ&sdn=java&zu=http%3A%2F%2Fwww.owlmountain.com%2Ftutorials%2FNonBlockingIo.htm) that does all the networking jazz. The problem is that when I shut the main window, the program doesn't actually exit.
This is what the main networking method looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public void acceptConnections() throws IOException, InterruptedException { SelectionKey acceptKey = selectableChannel.register( selector, SelectionKey.OP_ACCEPT ); System.out.println( "Acceptor loop..." ); while( ( keysAdded = acceptKey.selector().select() ) > 0 ) { System.out.println( "Selector returned " + keysAdded + " ready for IO operations" ); Set readyKeys = selector.selectedKeys(); Iterator i = readyKeys.iterator(); while( i.hasNext() ) { SelectionKey key = (SelectionKey)i.next(); i.remove(); if( key.isAcceptable() ) { ServerSocketChannel nextReady = (ServerSocketChannel)key.channel(); System.out.println( "Processing selection key" + " read=" + key.isReadable() + " write=" + key.isWritable() + " accept=" + key.isAcceptable() ); SocketChannel channel = nextReady.accept(); channel.configureBlocking( false ); SelectionKey readKey = channel.register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE ); readKey.attach( new ChannelCallback( channel ) ); } else if( key.isReadable() ) { SelectableChannel nextReady = (SelectableChannel)key.channel(); System.out.println( "Processing selection key" + " read=" + key.isReadable() + " write=" + key.isWritable() + " accept=" + key.isAcceptable() ); readMessage( (ChannelCallback)key.attachment() ); } else if( key.isWritable() ) { ChannelCallback callback = (ChannelCallback)key.attachment(); String message = "What is your name?"; ByteBuffer buf = ByteBuffer.wrap( message.getBytes() ); int nBytes = callback.getChannel().write( buf ); } } } System.out.println( "End acceptor loop." ); } |
From what I can tell, it just sort of sits at the 'while( blah blah )' until it gets something over the network, right? But since I haven't written a client yet, that never happens. hehe
For that matter, how can I hook up an event handler of some sort to catch when the application is shutting down, so that I can clean all this up?
Thanks in advance~