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:
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();
// Have to find a way to actually ... you know... do stuff.
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~